views:

63

answers:

3

Hi, 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.

A: 

The console tell you about the whole problem. Your Assignment object doesn't implement the method initWithCoder:

'NSInvalidArgumentException', reason: '-[Assignment initWithCoder:]: unrecognized selector sent to instance 0x5f04090'

The KeyArchiver will call your class to init a new object based on the decoding data. You should use [decoder objectForKey:YOUR_KEY];

vodkhang
I do implement it. [decoder objectForKey:YOUR_KEY]; is not available.
enbr
A: 

The problem isn't the NSMutableArray or how you are calling NSKeyedArchiver. The problem is that the objects inside the array are themselves not archivable.

You need your objects to implement the NSCoding protocol. There is plenty of documentation out there on how to do that, but basically you just add an initWithCoder: method to create the object out of an archive, and a encodeWithCoder: method to write the object to an archive. Piece of cake!

benzado
I implemented it but it still doesn't work.
enbr
+1  A: 

Fixed. I used Brad Larson's code at http://stackoverflow.com/questions/537044/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];
}
enbr
You could also write objectArray = [oldSavedArray mutableCopy]
benzado