How to auto clear NSUserDefault values in swift? [

2020-02-08 04:28发布

问题:

How can I auto clear the nsuserdefault values in swift? I have already tried this but it doesn't work for me...

[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];

回答1:

check how many keys are already stored

print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array.count)

add just another key

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "justAnotherKey1")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "justAnotherKey2")

check how many keys are already stored again (+2)

print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array.count)

now create a loop to remove your object for the keys

for key in NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys {
    NSUserDefaults.standardUserDefaults().removeObjectForKey(key.description)
}

check how many keys you have again

print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array.count)

update: Xcode 7.2.1 • Swift 2.1.1 (note NSUserDefaults doesn't work in playground anymore, so it needs to be tested in a real project)

print(Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys).count)

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "justAnotherKey1")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "justAnotherKey2")

print(Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys).count)

for key in Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys) {
    NSUserDefaults.standardUserDefaults().removeObjectForKey(key)
}

print(Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys).count)


回答2:

The swift counterpart for your objective-c code is this

 let appDomain = NSBundle.mainBundle().bundleIdentifier!

 NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)

Swift 3.0 and higher

let appDomain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: appDomain)


回答3:

Swift 3.0 Solution

let appDomain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: appDomain) 


回答4:

defaults.setObject(nil, forKey: "userEmail")

doing that, you put nil, so you clear



回答5:

There is no "auto clear". Just get all the existing NSUserDefaults keys and set them all to nil.

To get all the keys, get the NSUserDefaults dictionaryRepresentation and get its keys (allKeys in Objective-C).