Check if NSUserDefaults key exists

In my application, I save the key using this code:

func saveKey(){ var xmineSpillere = mineSpillere var defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(xmineSpillere, forKey: "YourKey") } 

But how can I check if a key exists? I want the code to look something like this:

 if key("YourKey") exists { println("key exists") } else { println("does not exist") } 

How can I do something like this in Swift?

+7
swift nsuserdefaults
source share
4 answers

First of all, every time you save any NSUserDefaults character, you need to call the synchronize() method to write any changes in the permanent domains to the disk and update all unmodified permanent domains to what is on the disk.

 func saveKey(){ var xmineSpillere = mineSpillere var defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(xmineSpillere, forKey: "YourKey") defaults.synchronize() } 

The synchronize method is automatically called at periodic intervals, use this method only if you cannot wait for automatic synchronization (for example, if your application is about to exit) or if you want to update the user’s default settings located on the disk, even if you didn’t no changes.

Then you can achieve any value as follows:

 if let key = NSUserDefaults.standardUserDefaults().objectForKey("YourKey"){ // exist } else { // not exist } 

Hope this helps you.

+18
source share

Found myself, the code:

 if (NSUserDefaults.standardUserDefaults().objectForKey("YourKey") != nil) { println("key exist") } 
+6
source share

Swift 3+

 if let key = UserDefaults.standard.object(forKey: "Key"){ // exist } else { // not exist } 
0
source share

Adding this extension to UserDefaults will help:

 extension UserDefaults { func contains(key: String) -> Bool { return UserDefaults.standard.object(forKey: key) != nil } } 

You can check if your key exists:

 if UserDefaults.contains(key: "YourKey") { print("Key exist") } else { print("Does not exist") } 
0
source share

All Articles