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];
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
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?
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