some_id
some_id

Reputation: 29886

Storing NSObjects in an NSMutableArray in NSUserDefaults

How does one store a NSMutableArray of NSObjects to NSUserDefaults successfully?

I tried a few things and it doesnt seem to work.

What is the correct way to do this?

Upvotes: 0

Views: 1230

Answers (2)

dreamlax
dreamlax

Reputation: 95315

From the NSUserDefaults documentation page:

Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value. For example, if you set a mutable string as the value for "MyStringDefault", the string you later retrieve using stringForKey: will be immutable.

You can always turn an immutable array into a mutable one with:

NSMutableArray *mutable = [NSMutableArray arrayWithArray:immutable];

As Zebs has already pointed out, you can only store plist-able objects into NSUserDefaults (NSString, NSArray, NSDictionary, NSData, NSDate and NSNumber). The documentation also states:

For NSArray and NSDictionary objects, their contents must be property list objects.

So, if your array contains custom objects, you cannot put it in NSUserDefaults.

Upvotes: 1

Zebs
Zebs

Reputation: 5438

From the documentation:

Note that a default’s value can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.

As such, you cannot store a custom NSObject.

What you can do is create a method that turns your object into a dictionary with keys.

You also need a method that turs that dictionary into your object.

Once you have NSObjects that are property list objects you can just use:

//ObjectA could be a representation of your object using an NSDictionary.
NSMutableArray *objects = [[NSMutableArray alloc] initWithObjects:objectA, objectB, objectC, nil];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:objects forKey:@"StoredArray"];
[objects release];
//To save changes immediately
[defaults synchronize];

Upvotes: 4

Related Questions