Bazinga
Bazinga

Reputation: 2466

saving NSMutableArray in NSUserDefaults

In my and successBlock below, Im saving the info to my NSMutableArray selectedPhotos. BTW, the info is a ALAsset url. URLs from my camera roll.

     } andSuccessBlock:^(NSArray *info) 
            [self.selectedPhotos setArray:info];

What I needed to do is save it via NSUserDefaults. Here is how I save it in NSUserDefaults:

            [[NSUserDefaults standardUserDefaults] setObject:self.selectedPhotos forKey:@"PickedImage"];
            self.selectedPhotos = [[NSUserDefaults standardUserDefaults] objectForKey:@"PickedImage"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            NSLog(@"SelectedPhotos:: %@", self.selectedPhotos);

But the problem is, when I log it it says NULL. How can I save my array via NSUserDefaults. Thanks for the help.

LOG:

SelectedPhotos:: (null)
*** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '(
    "ALAsset - Type:Photo, URLs:assets-library://asset/asset.JPG?id=119A0D2D-C267-4B69-A200-59890B2B0FE5&ext=JPG",
    "ALAsset - Type:Photo, URLs:assets-library://asset/asset.JPG?id=92A7A24F-D54B-496E-B250-542BBE37BE8C&ext=JPG",
    "ALAsset - Type:Photo, URLs:assets-library://asset/asset.JPG?id=77AC7205-68E6-4062-B80C-FC288DF96F24&ext=JPG" )' of class '__NSArrayM'.  Note that dictionaries and arrays in property lists must also contain only property values.

Upvotes: 0

Views: 1083

Answers (3)

Javal Nanda
Javal Nanda

Reputation: 1838

-Try saving it after archiving it (i.e converting to NSData) .Please have a look at the following answer Why NSUserDefaults failed to save NSMutableDictionary in iPhone SDK?

Upvotes: 0

user1617119
user1617119

Reputation:

To you save a NSMutableArray with ALAsset into the NSUserDefaults, you need to convert it in a NSData and save. Take a look:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:self.selectedPhotos];
[userDefaults setObject:arrayData forKey:@"selectedPhotos"];

And to log (and read) it, you need simple to:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSData *arrayData = [defaults objectForKey:@"selectedPhotos"];
NSLog(@"%@", [NSKeyedUnarchiver unarchiveObjectWithData:data]);

Upvotes: 0

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

Look at the log you got:

Note that dictionaries and arrays in property lists must also contain only property values.

An ALAsset is not valid for storage in NSUserDefaults. Only NSString, NSNumber, NSData, NSDate, NSArray, and NSDictionary can be stored there.

You must figure out what data from the asset you want to store, and store that. I suspect the URL is all you're really interested in storing, but without knowing what you plan to do with the data, I can't be sure.

Upvotes: 1

Related Questions