How to store custom objects in NSUserDefaults

后端 未结 7 1585
悲&欢浪女
悲&欢浪女 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:16

    If anybody is looking for a swift version:

    1) Create a custom class for your data

    class customData: 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.decodeObjectForKey("name") as! String
        self.url = aDecoder.decodeObjectForKey("url") as! String
        self.desc = aDecoder.decodeObjectForKey("desc") as! String
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.name, forKey: "name")
        aCoder.encodeObject(self.url, forKey: "url")
        aCoder.encodeObject(self.desc, forKey: "desc")
    } 
    }
    

    2) To save data use following function:

    func saveData()
        {
            let data  = NSKeyedArchiver.archivedDataWithRootObject(custom)
            let defaults = NSUserDefaults.standardUserDefaults()
            defaults.setObject(data, forKey:"customArray" )
        }
    

    3) To retrieve:

    if let data = NSUserDefaults.standardUserDefaults().objectForKey("customArray") as? NSData
            {
                 custom = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [customData]
            }
    

    Note: Here I am saving and retrieving an array of the custom class objects.

提交回复
热议问题