我创建了一个名为student
的课程,我希望使用NSUserDefaults
来存储和检索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")
我收到错误:Cannot assign value of type 'AnyObject?' to type '[student]'
答案 0 :(得分:2)
NSUserDefaults.standardUserDefaults().objectForKey("class")
期望AnyObject
类型的可选对象。您可以强行打开array of student.
//Retrieve data
classonestudents = NSUserDefaults.standardUserDefaults().objectForKey("class") as! [student]
但你应该经常检查它是否为零:
if let students = NSUserDefaults.standardUserDefaults().objectForKey("class") as? [student]
{
classonestudents = students
}
答案 1 :(得分:1)
只需使用以下代码更改最后一行代码即可修复错误:
classonestudents = NSUserDefaults.standardUserDefaults().objectForKey("class") as! [student]
希望,这会对你有帮助。