Walter West
Walter West

Reputation: 859

unexpectedly found nil when use userDefaults

I add @IBAction for button:

  @IBAction func addThemeAction(sender: AnyObject) {

        var userDefaults:NSUserDefaults=NSUserDefaults.standardUserDefaults()
        var itemList:NSMutableArray!=userDefaults.objectForKey("itemList") as NSMutableArray}

When I press button I get fatal error: unexpectedly found nil while unwrapping an Optional value.

Upvotes: 0

Views: 449

Answers (2)

Aaron Brager
Aaron Brager

Reputation: 66252

There's no object for the key itemList in your NSUserDefaults. Instead of force unwrapping it with !, check if optional is nil and conditionally unwrap it:

let userDefaults = NSUserDefaults.standardUserDefaults()

var itemList = userDefaults.objectForKey("itemList") as? [AnyObject]

if let itemList = itemList {
    // itemList is not nil, use it here
} else {
    // itemList has never been set, perhaps use some default
}

Also, userDefaults doesn't need to be a var.

You can change [AnyObject] to something else if you know the type (like [String], for example).

Upvotes: 0

gnasher729
gnasher729

Reputation: 52538

One: You can never guarantee that some key is present in your user defaults, so this is a crash waiting to happen. Two: I don't think dictionaries that you read from user defaults are mutable.

Upvotes: 0

Related Questions