How to store custom objects in NSUserDefaults

后端 未结 7 1579
悲&欢浪女
悲&欢浪女 2020-11-21 11:48

Alright, so I\'ve been doing some poking around, and I realize my problem, but I don\'t know how to fix it. I have made a custom class to hold some data. I make objects fo

7条回答
  •  无人共我
    2020-11-21 12:04

    Swift 3

    class MyObject: NSObject, NSCoding  {
        let name : String
        let url : String
        let desc : String
    
        init(tuple : (String,String,String)){
            self.name = tuple.0
            self.url = tuple.1
            self.desc = tuple.2
        }
        func getName() -> String {
            return name
        }
        func getURL() -> String{
            return url
        }
        func getDescription() -> String {
            return desc
        }
        func getTuple() -> (String, String, String) {
            return (self.name,self.url,self.desc)
        }
    
        required init(coder aDecoder: NSCoder) {
            self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
            self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
            self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
        }
    
        func encode(with aCoder: NSCoder) {
            aCoder.encode(self.name, forKey: "name")
            aCoder.encode(self.url, forKey: "url")
            aCoder.encode(self.desc, forKey: "desc")
        }
        }
    

    to store and retrieve:

    func save() {
                let data  = NSKeyedArchiver.archivedData(withRootObject: object)
                UserDefaults.standard.set(data, forKey:"customData" )
            }
            func get() -> MyObject? {
                guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
                return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
            }
    

提交回复
热议问题