Saving NSMutableArray to NSUserDefaults using NSKeyedArchiver

enbr picture enbr · Oct 17, 2010 · Viewed 9.2k times · Source

I'm having trouble retrieving a saved NSMutableArray containing a custom object. The app crashes and the console reports http://pastie.org/1226822. Here is my objects .h file http://pastie.org/1226823. Here is my objects .m file http://pastie.org/1226826. Here is how I save my data http://pastie.org/1226830. Here is how I retrieve my data http://pastie.org/1226831. Thanks in advance.

Answer

enbr picture enbr · Oct 17, 2010

Fixed. I used Brad Larson's code at Storing custom objects in an NSMutableArray in NSUserDefaults. I think that there was a problem with how I added the data back into my array, but it works now.

NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"savedArray"];
if (dataRepresentingSavedArray != nil)
{
    NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
    if (oldSavedArray != nil)
            objectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
    else
            objectArray = [[NSMutableArray alloc] init];
}