0
[[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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What if I want to use an NSMutableArray?
Note that the objects in the array must conform to the NSCoding protocol if they must be archived.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.