Search code examples
iosobjective-cnsarraynsuserdefaults

App crashes when storing NSArray in NSUserDefaults


I couldn't store an NSArray in NsUserDefaults. The app gets crashed
in this line [savedData setObject:jsonValue forKey:@"JSONDATA"];

Below is my code. and i have mention my log error below

NSArray *jsonValue =[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults];
[savedData setObject:jsonValue forKey:@"JSONDATA"];
[savedData synchronize];

Error log:

*** Terminating app due to uncaught exception '`NSInvalidArgumentException`', reason: '*** -

[NSUserDefaults setObject:forKey:]: attempt to insert non-property list object <CFBasicHash 0x8c62b10 [0x1d2aec8]>{type = immutable dict, count = 3,
    entries =>

Solution

  • Yes they can not be saved like this in NSUserDefaults.

    I am writing a code below please have a look and for more study go look apple docs okay.

    Code is here:

    //For Saving

    NSData *dataSave = [NSKeyedArchiver archivedDataWithRootObject:yourArrayToBeSave]];
    [[NSUserDefaults standardUserDefaults] setObject:dataSave forKey:@"array"];
    
    [[NSUserDefaults standardUserDefaults] synchronize]; // this will save you UserDefaults
    

    //For retrieving

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