Karl Kivi Karl Kivi - 2 months ago 25
iOS Question

NSUserDefaults nil after setting an object for key

I am facing an issue that I can't find help from google or other questions solving or giving me explaination related to

NSUserDefaults


let defaults = NSUserDefaults.standardUserDefaults()
let s = defaults.objectForKey("troll")

if s == nil {
defaults.setObject("This is important message", forKey: "troll")
defaults.synchronize()
}

print(s as! String) // It returns nil


it turns out if I try to access the object right after setting it, it returns nil!

BUT, if run my project again on my device then:

s as! String // returns "This is important message"


My question is WHY it's not returning string value instead of returning nil at the first time, but second project run time returns that string value.

I need it to return string value at the first time. Is that possible? Could someone point out that what am I doing wrong?

Thanks in advance!

Answer

You're going to kick yourself...

if s == nil {

So you just said that s is nil, I got it...

print(s as! String) // It returns nil

Well, what do you expect it to be, you just said it was nil! :-)

I think you meant to do this:

let s = defaults.objectForKey("troll")
if s == nil {
    s = "This is important message"
    defaults.setObject(s, forKey: "troll")
    defaults.synchronize()
}
print(s as! String) // no longer returns nil

You, sir, owe me a beer.