Saving NSMutableArray to NSUserDefaults using NSKeyedArchiver

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

+3
source share
3 answers

Fixed. I used Brad Larson's code in Saving custom objects in NSMutableArray in NSUserDefaults . I think there was a problem with the way I added the data back to my array, but now it works.

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];
}
+8
source

The console tells you the whole problem. Your object Assignmentdoes not implement a methodinitWithCoder:

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

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

+1
source

NSMutableArray, , NSKeyedArchiver. , .

NSCoding. , , initWithCoder: encodeWithCoder: . !

+1
source

Source: https://habr.com/ru/post/1769926/


All Articles