Reputation: 859
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
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
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