3

I want to store an integer in NSUserDefaults that could potentially be 0. How do I distinguish between an integer that was stored as 0 and a key that does not exist in NSUserDefaults?

According to the NSUserDefaults docs integerForKey returns 0 if the key did not exist in NSUserDefaults. So, my question is: how do I distinguish between a nonexistent key and a key I've stored as 0?

Eric Conner
  • 10,422
  • 6
  • 51
  • 67
  • One approach is to assume the value exists. If it doesn't, 0 is the default, but how is it different than if it exists and is 0? If you need a default value different than 0, use `NSUserDefaults.registerDefaults`, which will give default values to non existing keys, but will not override values of keys that do exist. – Léo Natan Apr 19 '15 at 20:27
  • Note that there is a third option: The key exists, but its value is not an integer. – Martin R Apr 19 '15 at 21:00

1 Answers1

4

You can check by using the objectForKey method because this method doesn't automatically returns 0 but returns nil, if the key doesn't exist:

if let yourInteger = NSUserDefaults.standardUserDefaults().objectForKey("yourKey"){
    //Key exists
}

You could create an extension for your NSUserDefaults to check:

extension NSUserDefaults {
    func hasKey(key: String) -> Bool {
        return objectForKey(key) != nil
    }
}
Christian
  • 22,585
  • 9
  • 80
  • 106