我有一个名为Person的自定义类,它在输入信息时存储有关某人的各种属性.
class Person { // Person dictionary variable var name: String? var age: String? var html_url: String? init(json: NSDictionary) { // Dictionary object self.name = json["name"] as? String self.age = json["age"] as? String self.html_url = json["html_url"] as? String // Location of the JSON file } }
创建字典后,将其放入数组中.点击按钮时,我在将数组保存到NSUserDefaults时遇到问题.
personArray.append(newPerson) // newPerson = dictionary of attributes NSUserDefaults.standardUserDefaults().setObject(personArray,forKey: "personArray") NSUserDefaults.standardUserDefaults().synchronize()
我看过How to store custom objects in NSUserDefaults和Saving custom SWIFT class with NSCoding to UserDefaults,但我没有运气,发现很难理解.
当我只是尝试保存到NSUserDefaults时,我被告知以下内容:
Attempt to set a non-property-list object ( "PersonApp.Person" ) as an NSUserDefaults/CFPreferences value for key personArray
解决方法
您的Person类应如下所示:
斯威夫特3:
class Person : NSObject,NSCoding{ // Person dictionary variable var name: String? var age: String? var html_url: String? init(json: NSDictionary) { // Dictionary object self.name = json["name"] as? String self.age = json["age"] as? String self.html_url = json["html_url"] as? String // Location of the JSON file } required init?(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as? String; self.age = aDecoder.decodeObjectForKey("age") as? String; self.html_url = aDecoder.decodeObjectForKey("html") as? String; } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.name,forKey: "name"); aCoder.encodeObject(self.age,forKey: "age"); aCoder.encodeObject(self.html_url,forKey: "html"); } }
在这里,您有一个从NSUserDefaults保存和检索数组的示例:
let p = Person() p.name = "person1" p.age = "12" p.html_url = "www.google.ro" let p2 = Person() p2.name = "person2" p2.age = "11" p2.html_url = "www.google.ro" let array = [p,p2] let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setValue(NSKeyedArchiver.archivedDataWithRootObject(array),forKey: "persons") userDefaults.synchronize() let array : [Person] array = NSKeyedUnarchiver.unarchiveObjectWithData(userDefaults.objectForKey("persons") as! NSData) as! [Person] print("\(array[0].name)\(array[1].name)")
斯威夫特4:
class Person : NSObject,NSCoding{ // Person dictionary variable var name: String? var age: String? var html_url: String? init(json: NSDictionary) { // Dictionary object self.name = json["name"] as? String self.age = json["age"] as? String self.html_url = json["html_url"] as? String // Location of the JSON file } required init?(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObject(forKey: "name") as? String; self.age = aDecoder.decodeObject(forKey: "age") as? String; self.html_url = aDecoder.decodeObject(forKey: "html") as? String; } func encode(with aCoder: NSCoder) { aCoder.encode(self.name,forKey: "name"); aCoder.encode(self.age,forKey: "age"); aCoder.encode(self.html_url,forKey: "html"); } }