JZonker JZonker - 6 months ago 10
Swift Question

Retrieve an array of objects using NSUserDefaults

I have created a class called

student
and I am looking to use
NSUserDefaults
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

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
}