5

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]; 
Marco
  • 6,692
  • 2
  • 27
  • 38
jdog
  • 10,351
  • 29
  • 90
  • 165

2 Answers2

5

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

Community
  • 1
  • 1
HepaKKes
  • 1,555
  • 13
  • 22
  • 1
    I would not misuse NSUserDefaults that much, it's primarily settings storage. But the solution is working, so +1. – pronebird Jul 08 '13 at 22:17
  • @Andy Good point, I totally agree with you...Anyway I tried to give an answer to the jgervin question. I might have caught the wrong question =) – HepaKKes Jul 08 '13 at 22:24
1

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?

Andrew
  • 15,357
  • 6
  • 66
  • 101