Attempt to insert non-property list object when trying to save a custom object in Swift 3

后端 未结 5 1862
北海茫月
北海茫月 2020-11-27 14:58

I have a simple object which conforms to the NSCoding protocol.

import Foundation

class JobCategory: NSObject, NSCoding {
    var id: Int
    v         


        
5条回答
  •  情话喂你
    2020-11-27 15:24

    Based on Harjot Singh answer. I've used like this:

    struct AppData {
    
        static var myObject: MyObject? {
    
            get {
                if UserDefaults.standard.object(forKey: "UserLocationKey") != nil {
                    if let data = UserDefaults.standard.value(forKey: "UserLocationKey") as? Data {
                        let myObject = try? PropertyListDecoder().decode(MyObject.self, from: data)
                        return myObject!
                    }
                }
                return nil
            }
    
            set {
                UserDefaults.standard.set(try? PropertyListEncoder().encode(newValue), forKey: "UserLocationKey")
            }
    
        }
    }
    

提交回复
热议问题