How to remove all data by a suite name from UserDefaults in Swift?

让人想犯罪 __ 提交于 2020-01-30 12:13:43

问题


I have created user defaults with names below,

let prefs1 = UserDefaults.init(suiteName: "UserAccount")
let prefs2 = UserDefaults.init(suiteName: "UserInfo")

Then I have added some values to those suites. i.e.

prefs1.set(true, forKey: "Key1")
prefs1.set(true, forKey: "Key2")

prefs2.set(false, forKey: "Key1")
prefs2.set(false, forKey: "Key2")

Now, I want to remove the prefs1 (i.e. name "UserAccount"), but not prefs2. I tried,

UserDefaults.standard.removePersistentDomain(forName: "UserAccount")

But it did not remove. I am getting confused with, forName and suiteName

How to remove a suite from UserDefaults keeping other suites intact in Swift?


回答1:


You can try

UserDefaults.standard.removeSuite(named: "UserAccount")

If you want to just remove the keys. You can go for following

func removeAllFor(defaults: UserDefaults) {
        let dictionary = defaults.dictionaryRepresentation()
        dictionary.keys.forEach { key in
            defaults.removeObject(forKey: key)
        }
    }

Then you can call it on default that you want to clear data for

removeAllFor(defaults: prefs1)

removeSuite(named:) : Removes a sub-searchlist added via -addSuiteNamed method

removePersistentDomain(forName: ) : Removes all values from the search list entry specified by ‘domainName’.




回答2:


I usually a different approach that also cleans up keys, based in idea "nil = no more exisiting":

// make property:

   var userName: String? {

        set(NewValue) {
            self.setUserDefault(value: NewValue, for: USERNAME_KEY)
        }
        get{
            let v =  self.getFromUserDefaultsWith(key: USERNAME_KEY) as? String
            return v
        }
    }

// accessory functions: (here the trick)

private final func getFromUserDefaultsWith(key: String) -> Any? {
    let returnValue  = UserDefaults.standard.object( forKey: key)
    return returnValue
}

private final func setUserDefault(value: Any?, for key: String) {
    let ud = UserDefaults.standard
    if value == nil{
        ud.removeObject(forKey: key)
    }else{
        ud.set(value, forKey:  key)
    }
    ud.synchronize()
}

SO I can write:

final func wipeOut() {
    // if nil, we remove... see above.
    self.setUserDefault(value: nil, for: USERNAME_KEY)
}


来源:https://stackoverflow.com/questions/58602607/how-to-remove-all-data-by-a-suite-name-from-userdefaults-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!