Attempt to set a non-property-list object as an NSUserDefaults

前端 未结 11 1719
闹比i
闹比i 2020-11-22 15:00

I thought I knew what was causing this error, but I can\'t seem to figure out what I did wrong.

Here is the full error message I am getting:

Attempt to se         


        
11条回答
  •  轮回少年
    2020-11-22 15:44

    Swift 3 Solution

    Simple utility class

    class ArchiveUtil {
    
        private static let PeopleKey = "PeopleKey"
    
        private static func archivePeople(people : [Human]) -> NSData {
    
            return NSKeyedArchiver.archivedData(withRootObject: people as NSArray) as NSData
        }
    
        static func loadPeople() -> [Human]? {
    
            if let unarchivedObject = UserDefaults.standard.object(forKey: PeopleKey) as? Data {
    
                return NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? [Human]
            }
    
            return nil
        }
    
        static func savePeople(people : [Human]?) {
    
            let archivedObject = archivePeople(people: people!)
            UserDefaults.standard.set(archivedObject, forKey: PeopleKey)
            UserDefaults.standard.synchronize()
        }
    
    }
    

    Model Class

    class Human: NSObject, NSCoding {
    
        var name:String?
        var age:Int?
    
        required init(n:String, a:Int) {
    
            name = n
            age = a
        }
    
    
        required init(coder aDecoder: NSCoder) {
    
            name = aDecoder.decodeObject(forKey: "name") as? String
            age = aDecoder.decodeInteger(forKey: "age")
        }
    
    
        public func encode(with aCoder: NSCoder) {
    
            aCoder.encode(name, forKey: "name")
            aCoder.encode(age, forKey: "age")
    
        }
    }
    

    How to call

    var people = [Human]()
    
    people.append(Human(n: "Sazzad", a: 21))
    people.append(Human(n: "Hissain", a: 22))
    people.append(Human(n: "Khan", a: 23))
    
    ArchiveUtil.savePeople(people: people)
    
    let others = ArchiveUtil.loadPeople()
    
    for human in others! {
    
        print("name = \(human.name!), age = \(human.age!)")
    }
    

提交回复
热议问题