(Swift) Storing and retrieving Array to NSUserDefaults
Asked Answered
T

7

22

I am trying to store an array to NSUserDefaults and retrieve the array when needed to populate a UITableView.

Currently I am using:

//store data
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")                    
NSUserDefaults.standardUserDefaults().synchronize()

//retrieve data
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
myArray = [tabledata!]
tableView.reloadData()

But I get

fatal error: unexpectedly found nil while unwrapping an Optional value

when trying to load the data. I am not sure if the issue is in the storage or the retrieval. Has anyone been through this before?

Trygve answered 8/5, 2015 at 7:58 Comment(0)
P
34

From your code I see you are storing some array

// Your code
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")

and retrieving a string

//Your code
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")

There is probably a type mismatch, You store one type and retrieve another type.

While retrieving either use arrayForKey() or objectForKey() see the code below.

let tabledata = NSUserDefaults.standardUserDefaults().arrayForKey("\(identity.text!)listA") 

or

let tabledata = NSUserDefaults.standardUserDefaults().objectForKey("\(identity.text!)listA")

If it is an array I would go with First one.

Patroon answered 8/5, 2015 at 8:15 Comment(0)
S
11

Here are the way that you can store and retrieved array of object with help of NSKeyArchive.

To Store array to NSUserDefault.

let placesData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(placesData, forKey: "places")

To Retrieved array from NSUserDefault.

let placesData = UserDefaults.standard.object(forKey: "places") as? NSData

if let placesData = placesData {
    let placesArray = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? [Place]
    print(placesArray)
}

Hope this help you.

Sinotibetan answered 8/5, 2015 at 9:56 Comment(1)
For custom object array it's not working can you please help me out. let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: customeobject array)Eolande
P
10

Saving and Retrieving a String array to UserDefaults

Save array

let array = ["horse", "cow", "camel", "sheep", "goat"]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")

Retrieve array

let defaults = UserDefaults.standard
let array = defaults.object(forKey: "SavedStringArray") as? [String] ?? [String]()

See more at How to save user settings using NSUserDefaults

Peltate answered 21/5, 2016 at 1:8 Comment(0)
E
2

What are you storing in the array?

If it's objects it won't work, if It's just strings or numbers then it should be fine.

Next steps you take should be to turn on exception breakpoints and maybe println() everything you can so you can pinpoint the exact whereabouts of the problem.

As a shot in the dark I would suggest maybe (identity.text!) is coming out as nil

Also you should probably change it to this

if let tabledata: NSArray = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA"){

    myArray = [tabledata!]

    tableView.reloadData()
}

This will make the code not even try to run unless there is a value it can use

Emit answered 8/5, 2015 at 8:9 Comment(2)
I printed identity.text! and that is working properly. So the issue is not there. I tried running your code but I still get the same error.Trygve
println("(tabledata)') is what is returning nilTrygve
D
2

Latest swift3 version to store array of data into userdefaults and get that array of data using keys

    let nameArray = ["Ramu","JAGAN","Steve","Swift"]
    let namesArrayData = NSKeyedArchiver.archivedData(withRootObject: nameArray)
    UserDefaults.standard.set(namesArrayData, forKey: "arrayData")

RetriveData

        let retriveArrayData= UserDefaults.standard.object(forKey:  "arrayData") as? NSData

   if let retriveArrayData= namesArrayData{
  let retriveArray = NSKeyedUnarchiver.unarchiveObject(with: namesArraydata as Data) as? [nameArray]
  print(retriveArray )
}
Delusive answered 26/3, 2017 at 18:11 Comment(0)
A
1

This has been changed in swift 3. Note that this works with device but not playground or simulator

//store the array
let array = ["horse", "cow", "camel", "sheep", "goat"]

let defaults = UserDefaults.standard

defaults.setValue(array, forKey: "history")

defaults.synchronize()

//Retrieve the array
if((UserDefaults.standard.array(forKey: "history")) != nil){
    let historyWords = (UserDefaults.standard.array(forKey: "history") as? [String])!
    print(historyWords)
}
Aldis answered 15/11, 2016 at 15:34 Comment(0)
S
-1

Store into User Default:

let arrayFruit = ["Apple","Banana","Orange","Grapes","Watermelon"]    
 //store in user default
UserDefaults.standard.set(arrayFruit, forKey: "arrayFruit")

Retrieving array from User Defaults:

if let arr = UserDefaults.standard.array(forKey: "arrayFruit") as? [String]{
    print(arr)
}
Suttles answered 26/3, 2018 at 9:58 Comment(1)
Ya ill take care of it. Thanks @MoritzSuttles

© 2022 - 2024 — McMap. All rights reserved.