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 =>
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];
While kshitij's answer is correct, sadly, it doesn't end there. If you want to save custom objects inside your NSUserDefaults
, your custom object has to implement the NSCoding
protocol and override the initWithCoder
and encodeWithCoder
methods. An example of such can be like:
@interface Book : NSObject <NSCoding>
@property NSString *title;
@property NSString *author;
@property NSUInteger pageCount;
@property NSSet *categories;
@property (getter = isAvailable) BOOL available;
@end
@implementation Book
#pragma mark - NSCoding
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (!self) {
return nil;
}
self.title = [decoder decodeObjectForKey:@"title"];
self.author = [decoder decodeObjectForKey:@"author"];
self.pageCount = [decoder decodeIntegerForKey:@"pageCount"];
self.categories = [decoder decodeObjectForKey:@"categories"];
self.available = [decoder decodeBoolForKey:@"available"];
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.title forKey:@"title"];
[encoder encodeObject:self.author forKey:@"author"];
[encoder encodeInteger:self.pageCount forKey:@"pageCount"];
[encoder encodeObject:self.categories forKey:@"categories"];
[encoder encodeBool:[self isAvailable] forKey:@"available"];
}
@end
try like this
NSMutableArray *jsonValue =[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSData *yourEncodedObject = [NSKeyedArchiver archivedDataWithRootObject: jsonValue];
NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults];
[userData setObject: yourEncodedObject forKey:@"JSONDATA"];
[savedData synchronize];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With