views:

56

answers:

1
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];

If I make an array of custom objects conform to the NSCoding protocol, then does the above work? Do I have to make both the custom class and the view controller that holds the array of custom objects conform to the NSCoding protocol or just the custom class? Do I have to use NSKeyedArchiver somewhere?

+2  A: 

It looks like you will need to archive your array, either with NSKeyedArchiver or NSArchiver. If you first archive the array into a NSData object:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray];

You can then store that data in NSUserDefaults like so:

[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"myArray"];

To load the array, use:

NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"myArray"];
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];

If you want to use an NSMutableArray then just replace any NSArray occurrences in the code above with NSMutableArray. OR you can just NSMutableArray *myMutableArray = [myArray mutableCopy] will give you a NSMutableArray to work with.

But then hey, if you are going to the trouble of making it NSCoding compliant, why not just archive it to a file?

The documentation that made me think that you will need to use an archiver is here so that you can check for yourself.

cool_me5000
What is the code to load the array?
awakeFromNib
Fixed my answer to show how to load.
cool_me5000
What if I want to use an NSMutableArray?
awakeFromNib
Note that the objects in the array must conform to the `NSCoding` protocol if they must be archived.
Alexsander Akers