问题
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