NSUserDefaults返回空数组

时间:2016-10-28 08:44:41

标签: ios swift nsuserdefaults

我有一个Person类,它是一个模型

import Foundation

public class Person : NSObject , NSCoding{ 
public var name:String="";
public var gender:Int = 0;
public var status:Int = 0

    override init (){
        super.init()
    }

    public init (name:String, gender:Int){
    self.name=name;
    self.gender=gender;
}    
    required public init(coder aDecoder: NSCoder) {   }
    public func encodeWithCoder(_aCoder: NSCoder) {   }

}

现在,当我尝试检索[Person]数组时,我使用方法getPersons(arr : String!)。如果NSUserDefaults中没有数据,我创建它,将1个元素放入其中并使用setPersons()方法存储。

问题在于,在检索时我得到一个具有正确count(1)的数组,但该对象未填充,在String中为“”,在Int变量中为0。

 private func archivePeople (people : [Person]) -> NSData{
        return NSKeyedArchiver.archivedDataWithRootObject(people as NSArray)
    }

    public func getPersons(arr : String!) -> [Person]{
        var array : [Person] = []
        if let unarchivedObject = NSUserDefaults.standardUserDefaults().objectForKey(arr) as? NSData {
            array = (NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as? [Person])!
        }

       if array.count == 0 {
            array.append(Person(name: A.DEFAULT_THEIR_NAMES,gender: 0))
            setPersons(arr, people: array)
        }
        return array
    }

    public func setPersons(key: String, people : [Person]){
         let archivedObject = archivePeople(people)
        userDefaults.setObject(archivedObject, forKey: key)
        userDefaults.synchronize()
    }

有什么问题?我是否以错误的方式设置或检索此内容?

1 个答案:

答案 0 :(得分:3)

您需要正确覆盖NSCoding个功能。 它应该看起来像下面的代码:

 required public convenience init(coder aDecoder: NSCoder) {
        let name: String = aDecoder.decodeObject(forKey: "name") as! String
        let gender = aDecoder.decodeInt64(forKey: "gender")
        let status = aDecoder.decodeInt64(forKey: "status")
        self.init(name: name, gender: Int(gender))
        self.status = Int(status)
    }

    public func encodeWithCoder(_aCoder: NSCoder) {   
        _aCoder.encode(self.name, forKey: "name")
        _aCoder.encode(Int64(self.gender), forKey: "gender")
        _aCoder.encode(Int64(self.status), forKey: "status")
    }