1

I am trying store & get data in NSUserDefaults, when application launch at first time value for "token" in NSUserDefaults is nil. On application launch I am trying to get it from standardUserDefaults(), but it fails & give an error as:

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

Follow is the code:

var prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let value : AnyObject! = prefs.objectForKey("token") as AnyObject!
OnkarK
  • 3,745
  • 2
  • 26
  • 33

3 Answers3

1

That's exactly what I would expect if there is no object for the key "token".

AnyObject! means "you are allowed to assign values that might be nil, but I guarantee it won't happen, so please crash when it happens".

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • You are wrong. The value of `value` can be nil. This is all what `AnyObject!` means. This is not an assert statement. – Rafał Sroka Jul 16 '14 at 09:26
  • @reecon That is not the use case of AnyObject!, it means: Once set to a value it may not be nil anymore. Technically it could, but you should not test AnyObject! for nil. gnasher729 is absolutely correct. By convention from Apple AnyObject! should not be nil after first set. – Binarian Jul 16 '14 at 11:13
1

I am able to run your code without any problems in Xcode 6 Beta 2. Try updating to the latest Xcode 6 beta from developer center.

Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
-1

There is no problem with your code. I'm able to run it.

pref: AnyObject! = {
    value = None
}

What's the version of your Xcode?

Ch0c0late
  • 19
  • 3