使用NSUserDefaults保存自定义类数组

时间:2015-08-04 12:29:59

标签: ios xcode swift nsuserdefaults

我有一个名为Friend的自定义类:

class Friend {

    var fullName: String
    var birthday: String
    var from: String

    var photoLink: String = ""
    var photo: UIImage = UIImage()
    var photos: [AnyObject] = [AnyObject]()

    init(fullname: String, birthday: String, gotFrom: String) {
        self.fullName = fullname
        self.birthday = birthday
        self.from = gotFrom
    }
} 

我尝试使用NSUserDefaults保存它但是因为我使用自定义类而出错。

如何保存朋友阵列?

1 个答案:

答案 0 :(得分:3)

以下是您从NSUserDefaults保存和检索课程的简单示例:

    //your class
    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") }


        }

    }

//store values in class and store it to NSUserDefaults
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")

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

用操场测试。

希望这个例子有所帮助。