JZonker JZonker - 1 year ago 71
Swift Question

Retrieve an array of objects using NSUserDefaults

I have created a class called

and I am looking to use
to store and retrieve an
array of student.

//Establish array
var classonestudents = [student] ()
class student {
var name = String ()
var C4Role = 0
var LastTeam = 0
//This array is filled up by the user

//Store data
NSUserDefaults.standardUserDefaults().setObject(classonestudents, forKey: "class")

//Retrieve data
classonestudents = NSUserDefaults.standardUserDefaults().objectForKey("class")

I am getting the error :
Cannot assign value of type 'AnyObject?' to type '[student]'

Answer Source

NSUserDefaults.standardUserDefaults().objectForKey("class") expects optional object of type AnyObject. You can force unwrap in array of student.

//Retrieve data
classonestudents = NSUserDefaults.standardUserDefaults().objectForKey("class") as! [student]

But you should always check if its nil :

if let students = NSUserDefaults.standardUserDefaults().objectForKey("class") as? [student]
    classonestudents = students
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download