Saving NSArray to NSUserDefaults not working

I am trying to save NSArray objects in NSUserDefaults , but when I pull the NSArray back using getObject , it does not contain anything.

I set a breakpoint for counting objects and checking for elements in the array

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

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

 NSArray *allAmbulances = [[NSUserDefaults standardUserDefaults] objectForKey:kArrayOfFoundThings]; 
+4
source share
2 answers

Suppose the objects contained in your array conform to the NSCoding protocol, you can use

 // let 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 comply with the NSCopying protocol, then

 // let take the NSString as example NSArray *array = @[@"foo", @"bar"]; [[NSUserDefaults standardUserDefaults] setObject: array forKey:@"annotationKey"]; NSArray *archivedArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"annotationKey"] ; 

EDIT

Well, it may not work for NSArray objects that conform to the NSCopying protocol, but it may work for objects that conform to the NSCoding protocol, as pointed out by Brad Larson in the following answer:

Saving custom objects in NSMutableArray in NSUserDefaults

+4
source

Documentation:

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

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

+1
source

Source: https://habr.com/ru/post/1490365/


All Articles