Sumeet Purohit
Sumeet Purohit

Reputation: 667

User defaults gives nil value in Swift 3.0

I am new to swift and trying to store NSMutableArray in Userdefaults. Here is what I am doinig :

//to save aaray in user defaults
var set:NSMutableArray = NSMutableArray(objects: self.listId)
  self.saveListIdArray(set)

func saveListIdArray(_ params: NSMutableArray = []) {
let defaults = UserDefaults.standard
defaults.set(params, forKey: "ArrayKey")
defaults.synchronize()

}

//to get array from user default
func getUserDefaultKeyForAllObject(key userDefaultsKey: String) -> NSMutableArray {
let array = UserDefaults.standard.object(forKey: NSUserDefaultsKey.LIST_ID_ARRAY) as! NSMutableArray
print(array)
return array

}

App crashes with "fatal error: unexpectedly found nil while unwrapping an Optional value" exception.

Ignore the way I ask the question, help me out here.

Thank you.

Upvotes: 2

Views: 3260

Answers (3)

SveinnV
SveinnV

Reputation: 184

I have 2 possible reasons for this:

  1. You need to be 100% sure that you are retrieving array with the same key as you save it with. In your code you are saving the array with "ArrayKey" but retrieving it with NSUserDefaultsKey.LIST_ID_ARRAY, are you sure this is the same string?
  2. What datatype is self.listId? If it's a custom class then you need to make that class conform to the nscoding protocol, then encode it to Data and save that to the userDefaults (Save custom objects into NSUserDefaults)

A 3rd reason is that you are trying to get an object from the defaults without ever writing anything to it. Try changing

let array = UserDefaults.standard.object(forKey: NSUserDefaultsKey.LIST_ID_ARRAY) as! NSMutableArray
print(array)
return array

to

if let array = UserDefaults.standard.object(forKey: "ArrayKey") as? NSMutableArray {
   print(array)
   return array
}
else {
   return NSMutableArray()
}

Upvotes: 1

DHEERAJ
DHEERAJ

Reputation: 1468

Try converting to NSData then storing to nsuserdefaults like below

func saveListIdArray(_ params: NSMutableArray = []) {
let data = NSKeyedArchiver.archivedData(withRootObject: params) 

UserDefaults.standard.set(data, forKey: "test")
UserDefaults.standard.synchronize()
}

For retrieving the data use

if let data = UserDefaults.standard.object(forKey: "test") as? Data {
    if let storedData = NSKeyedUnarchiver.unarchiveObject(with: data) as? NSMutableArray 
{
            // In here you can access your array
}
}

Upvotes: 4

Jitendra Solanki
Jitendra Solanki

Reputation: 772

You are force unwrapping the NSMutableArray for a key. Don't force unwrap when you try to get the value from a dictionary or UserDefault for a key because there may be a chance that the value does not exist for that key and force unwrapping will crash your app.

Do this as:

 //to get array from user default
 if  let array = UserDefaults.standard.object(forKey:"ArrayKey") as? NSMutableArray
    print(array)
  }

Upvotes: 1

Related Questions