NSUserDefaults will not save NSDictionary

I am writing an application that uses NSUserDefaults as a data storage mechanism, and I encounter a problem when trying to save data (which correspond to property list protocols):

+ (BOOL)storeAlbum:(Album *)album { NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; NSMutableDictionary *albums = (NSMutableDictionary *)[prefs objectForKey:@"my_adventure_book_albums"]; NSLog(@"Existing albums: %@",albums); if (!albums) albums = [NSMutableDictionary dictionaryWithObject:album forKey:@"album"]; else [albums setObject:album forKey:@"album"]; NSLog(@"%@",album); [prefs setObject:albums forKey:@"my_adventure_book_albums"]; return [prefs synchronize]; } 

I get this output:

 2010-06-29 17:17:09.929 MyAdventureBook[39892:207] Existing albums: (null) 2010-06-29 17:17:09.930 MyAdventureBook[39892:207] test 2010-06-29 17:17:09.931 MyAdventureBook[39892:207] *** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '{ album = test; }' of class 'NSCFDictionary'. 

The album description method is as follows:

 - (NSString *)description { // Convert to a NSDictionary for serializing if (!title) title = @""; if (!date) date = [NSDate dateWithTimeIntervalSinceNow:0]; if (!coverImage) coverImage = @""; if (!images) images = [[NSArray alloc] initWithObjects:@"",nil]; //NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:title,date,coverImage,images,nil] forKeys:[NSArray arrayWithObjects:@"title",@"date",@"coverImage",@"images",nil]]; //NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:title,nil] forKeys:[NSArray arrayWithObjects:@"title",nil]]; //return [dict description]; return @"test"; } 

All commented lines have the same result, so I just decided to see if the NSString "test" would work, which it (of course) does not.

+2
source share
3 answers

But the object that you put inside the dictionary, Album* , is most likely not an object of the property list, is it? Every object, down to it, must have a property list object for this to work. The description method is not good enough for this to happen.

As a workaround, you can use NSCoding and NSKeyedArchiver to write your dictionary to NSData , which you can save among your settings.

+8
source

In the list of properties you can put the basic types of foundation. NSUserDefaults records preferences as a list of properties. See here for a list of properties of allowed types. In short, these are numbers, strings, data, dates, as well as arrays and dictionaries from them. Dictionaries must have string keys.

+5
source

NSUserDefaults always returns immutable objects, so you cannot just switch them to mutable. Make [prefs objectForKey:@"my_adventure_book_albums"] mutableCopy] (and don't forget to free it when you're done).

+4
source

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


All Articles