NSKeyedArchiver does not work in Swift 3 ( XCode 8)

后端 未结 4 531
悲哀的现实
悲哀的现实 2021-02-02 14:41

I have migrated my project to Swift 3 and NSKeyedArchiver does not work. I actually have a runtime error when trying to decode object like this:

let         


        
4条回答
  •  粉色の甜心
    2021-02-02 15:10

    Here is solution:

    class Person: NSObject, NSCoding {
    let name: String
    let age: Int
    required init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    required init(coder decoder: NSCoder) {
        self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
        self.age = decoder.decodeInteger(forKey: "age")
    }
    
    func encode(with coder: NSCoder) {
        coder.encode(name, forKey: "name")
        coder.encode(age, forKey: "age")
    }}
    

    How to use:

    class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let newPerson = Person(name: "Joe", age: 10)
        var people = [Person]()
        people.append(newPerson)
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: people)
        UserDefaults.standard().set(encodedData, forKey: "people")
        if let data = UserDefaults.standard().data(forKey: "people"),
            myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Person] {
            myPeopleList.forEach({print( $0.name, $0.age)})  // Joe 10
        } else {
            print("There is an issue")
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }}
    

    Reference: Swift 3 saving and retrieving custom object from userDefaults

提交回复
热议问题