PopKernel
PopKernel

Reputation: 4270

Array has error after being retrieved from NSUserDefaults

I have a custom class for which I've implemented the NSCoder protocol. My intended data model is to store an array of these custom classes in NSUserDefaults. I encode it as NSData and store it in an array, which I store in NSUserDefaults. However when I retrieve the stored data from NSUserDefaults the array does not contain the values I initially set. Here is an example, a couple lines of code, some there explicitly for debugging:

let values = Subject(name: self.name.text, instructor: self.instructor.text, time: self.time.date, assignments:nil) //Create my custom class
let archivedValues = NSKeyedArchiver.archivedDataWithRootObject(values) //Archive as NSData
var testarr = [archivedValues] //Store as Array<NSData>
NSUserDefaults.standardUserDefaults().setObject(testarr, forKey: "subjects") //Commit to NSUserDefaults
var subjectArray = NSUserDefaults.standardUserDefaults().arrayForKey("subjects") as Array<NSData> //Retrieve array

However the contents of these two arrays are different. The printed description:

Printing description of testarr:
([NSData]) testarr = 1 value {
[0] = 0x00007f9998e89440 445 bytes
}
Printing description of subjectArray:
([NSData]) subjectArray = 1 value {
[0] = <error: use of undeclared identifier 'cocoarr'
error: 1 errors parsing expression
>

The retrieved subjectArray seems to imply an error that occurred. However, it is an error I don't understand.

Upvotes: 0

Views: 132

Answers (2)

Ian
Ian

Reputation: 12768

You are all out of order with how you are saving the data. Instead of making it an array of NSData, make it an array of subjects and then archive that as NSData.

let subject1 = Subject(name: self.name.text, instructor: self.instructor.text, time: self.time.date, assignments:nil) //Create my custom class
let array = [subject1]

let data = NSKeyedArchiver.archivedDataWithRootObject(array)
let defaults = NSUserDefaults.standardUserDefaults()

// Storing the data
defaults.setObject(data, forKey: "subjects")

// Retrieving the data
if let data = defaults.objectForKey("subjects") as? NSData {
    if let subjects = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Subject] {
            // Now you have your subjects as [Subject]
    }
}

Upvotes: 1

Christian
Christian

Reputation: 22343

You did not add an array to the NSUserDefaults but a normal object. So that means that you can't get it with the arrayForKey method. You have to get it as:

var subjectArray = NSUserDefaults.standardUserDefaults().objectForKey("subjects")  

Upvotes: 0

Related Questions