Search code examples
iosswiftnsuserdefaults

UserDefaults return 0 elements when call in awakeFromNib


I have an UICollectionView inside UITableViewCell and I'm using UserDefaults to save an array of the selected item in didSelectItem function to keep selected state after dismissing the parent view controller of them:

var arrSelectedIndex = [IndexPath]()
let encodedData = NSKeyedArchiver.archivedData(withRootObject: arrSelectedIndex)
UserDefaults.standard.set(encodedData, forKey: "arrayOfSelectedItem")
UserDefaults.standard.synchronize()

And whenever I show up the view controller I set my array with UserDefaults again in awakeFromNib:

arrSelectedIndex = UserDefaults.standard.array(forKey: "arrayOfSelectedItem") as? [IndexPath] ?? [IndexPath]()

But both my array and the UserDefaults return 0 elements (I tried to print out value of arrSelectedIndex and UserDefaults.standard.array(forKey: "arrayOfSelectedItem") as? [IndexPath] ?? [IndexPath]()) and both of them is 0 even if they have data when selected item. Does awakeFromNib reset all things inside it?


Solution

  • First thing is to save the list in userDefault it not necessary to archive it, You can if contains basic data types. Second, If you archive the list before saving it to UserDefault, Then You have to unarchive the encoded data to get the list.

    Here is the method,

    data = UserDefaults.standard.data(forKey: "arrayOfSelectedItem") as? Data
    arrSelectedIndex = NSKeyedUnarchiver.unarchiveObject(with: data) as? [IndexPath] ?? [IndexPath]()
    

    Hope this will help.