Converting custom class object into NSData

后端 未结 3 905
清歌不尽
清歌不尽 2021-02-01 03:20

I have a custom class that I want to save into NSUserDefaults. I am told that I need to convert the class object into data in order to save it to NSUserDefaul

3条回答
  •  耶瑟儿~
    2021-02-01 04:05

    Here is one simple example for you:

    //Custom 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") }
    
        }
    }
    
    //create an instance of your custom class.
    var newPerson = [Person]()
    
    //add some values into custom class.
    newPerson.append(Person(name: "Leo", age: 45))
    newPerson.append(Person(name: "Dharmesh", age: 25))
    
    //store you class object into NSUserDefaults.
    let personData = NSKeyedArchiver.archivedDataWithRootObject(newPerson)
    NSUserDefaults().setObject(personData, forKey: "personData")
    
    
    //get your object from NSUserDefaults.
    if let loadedData = NSUserDefaults().dataForKey("personData") {
    
        if let loadedPerson = NSKeyedUnarchiver.unarchiveObjectWithData(loadedData) as? [Person] {
            loadedPerson[0].name   //"Leo"
            loadedPerson[0].age    //45
        }
    }
    

    Tested with playground.

    Hope this helps.

提交回复
热议问题