如何从NSUserDefaults swift保存和检索类对象?

时间:2015-07-09 09:24:03

标签: arrays swift nsuserdefaults nskeyedarchiver

我试图将我的数组保存到NSUserDefaults。但是我的数组存在于struct。

struct MyData {
    var Text = String()
    var Number = Int()
}

var Data = [MyData]()

我找到了this,我试图这样做;

let Data2 = NSKeyedArchiver.archivedDataWithRootObject(Data)

但这给了我这个:Cannot invoke 'archivedDataWithRootObject' with an argument list of type '([(TableViewController.MyData)])'

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

Swift structs不是classes,因此他们不符合AnyObject协议。

archivedDataWithRootObject的语法是:

class func archivedDataWithRootObject(rootObject: AnyObject) -> NSData

这意味着它只接受AnyObject类型对象而struct不符合AnyObject协议,因此您无法在此使用struct

所以只需将struct更改为class即可。

<强>更新

这样您就可以将其存储到NSUserDefaults

使用playGround测试

import UIKit

class Person: NSObject, NSCoding {
    var name: String!
    var age: Int!
    required convenience init(coder decoder: NSCoder) {
        self.init()
        self.name = decoder.decodeObjectForKey("name") as! String
        self.age = decoder.decodeObjectForKey("age") as! Int
    }
    convenience init(name: String, age: Int) {
        self.init()
        self.name = name
        self.age = age
    }
    func encodeWithCoder(coder: NSCoder) {
        if let name = name { coder.encodeObject(name, forKey: "name") }
        if let age = age { coder.encodeObject(age, forKey: "age") }


    }

}

var newPerson = [Person]()
newPerson.append(Person(name: "Leo", age: 45))
newPerson.append(Person(name: "Dharmesh", age: 25))
let personData = NSKeyedArchiver.archivedDataWithRootObject(newPerson)
NSUserDefaults().setObject(personData, forKey: "personData")

if let loadedData = NSUserDefaults().dataForKey("personData") {
    loadedData
    if let loadedPerson = NSKeyedUnarchiver.unarchiveObjectWithData(loadedData) as? [Person] {
        loadedPerson[0].name   //"Leo"
        loadedPerson[0].age    //45
    }
}