Search code examples
iosnsuserdefaultsdata-persistence

Why does NSUserDefaults always return nil?


I'm testing this code in playground. What I don't understand is, why is result always nil? Thanks for help

var value: String!
let key = "key24"

if value == nil{
    value = "hehe"
    let valueNS = NSString(string: value)


    NSUserDefaults.standardUserDefaults().setValue(valueNS, forKey: key)
}



var result: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey(key)
print(result)

enter image description here


Solution

  • There's something screwy going on with playgrounds, especially with Xcode 7. I can get a variation on your code to work on Xcode 6.4, with a few changes:

    You should use setObject:forKey not setValue:forKey.

    You should cal synchronize after changing defaults.

    Here's the modified code (which works in Xcode 6.4, although testing it in Xcode then causes Xcode 6.4 to fail as well.)

    //: Playground - noun: a place where people can play
    
    import UIKit
    
    var value: String!
    let key = "key24"
    
    
    if value == nil
    {
      value = "hehe"
      print("value was nil!")
      NSUserDefaults.standardUserDefaults().setObject(value, forKey: key)
      NSUserDefaults.standardUserDefaults().synchronize()
    }
    
    var result = NSUserDefaults.standardUserDefaults().stringForKey(key)
    print(result)