user3745888
user3745888

Reputation: 6353

How to save in NSUserDefaults a array of object?

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))
    }
}

Upvotes: 3

Views: 1547

Answers (1)

Caleb
Caleb

Reputation: 125017

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.

Upvotes: 5

Related Questions