How to save in NSUserDefaults a array of object?

倾然丶 夕夏残阳落幕 提交于 2019-12-06 06:58:35

问题


I need save in NSUserDefaults an array or other structure of data to save objects with this format:

name = "myName", lastName = "myLastName"

I was trying to do this with an array of arrays but this can't save in NSUserDefaults.

Now I am trying with a custom class with structure to create objects and append to the array, but also get an error when trying to save this to NSUserDefaults. I need save with this structure, but I don't know what is the correct form. How would I do this?

var taskMgr: TaskManager = TaskManager()

struct task {
    var name = "Un-Named"
    var lastName = "Un-lastNamed"
}

class TaskManager: NSObject {

    var tasks : [task] = []

    func addTask(name : String, lastName: String){
        tasks.append(task(name: name, lastName: desc))
    }
}

回答1:


NSUserDefaults expects the stored objects to all be property list objects, i.e. instances of NSArray, NSDictionary, NSString, NSNumber, NSData, or NSDate. Your struct isn't one of those. You'll need to convert your objects to property list types before you store them. One way to do that is to use NSKeyedArchiver and the NSCoding protocol to write your structs into an instance of NSData.



来源:https://stackoverflow.com/questions/25229478/how-to-save-in-nsuserdefaults-a-array-of-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!