Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving NSArray to NSUserDefaults is not working

I'm trying to save an NSArray of objects to NSUserDefaults, but when I pull the NSArray back out with getObject it contains nothing.

I put a break point here to count objects and verify there are items in the array

[[NSUserDefaults standardUserDefaults] setObject:mappingResult.array forKey:kArrayOfFoundThings];
[[NSUserDefaults standardUserDefaults] synchronize];

Here is where I pull them out and the array says nothing is inside.

NSArray *allAmbulances = [[NSUserDefaults standardUserDefaults] objectForKey:kArrayOfFoundThings]; 
like image 422
jdog Avatar asked Jul 08 '13 19:07

jdog


2 Answers

Supposing that objects contained in your array are conforming to the NSCoding protocol, you could use

// let's take the NSString as example
NSArray *array = @[@"foo", @"bar"];

[[NSUserDefaults standardUserDefaults] setObject: [NSKeyedArchiver archivedDataWithRootObject:array] forKey:@"annotationKey"];
NSArray *archivedArray = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"annotationKey"]] ;

If they are conform to the NSCopying protocol, then

// let's take the NSString as example
NSArray *array = @[@"foo", @"bar"];

[[NSUserDefaults standardUserDefaults] setObject: array forKey:@"annotationKey"];
NSArray *archivedArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"annotationKey"] ;

EDIT

Ok, probably it's not working for NSArray of objects conforming to NSCopying protocol, but it arguably works for the objects conforming to the NSCoding protocol as pointed out by Brad Larson in the following answer:

Storing custom objects in an NSMutableArray in NSUserDefaults

like image 188
HepaKKes Avatar answered Oct 12 '22 12:10

HepaKKes


Documentation:

The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects.

Are the contents of the array NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary objects?

like image 40
Andrew Avatar answered Oct 12 '22 13:10

Andrew