NSUserDefaults不会保存NSDictionary [英] NSUserDefaults won't save NSDictionary
问题描述
我正在编写一个使用NSUserDefaults作为数据存储机制的应用程序,在尝试保存数据时遇到问题(符合Property List协议):
I'm writing an application which uses NSUserDefaults as the data storage mechanism, and am hitting a problem when trying to save data (that conforms to the 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];
}
我得到这个输出:
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'.
相册的描述方法如下:
- (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";
}
所有注释掉的行都有相同的结果,所以我决定看看NSStringtest是否有效,它(当然)没有。
All of the commented-out lines have the same result, so I just decided to see if the NSString "test" would work, which it (of course) doesn't.
推荐答案
但对象你放在字典里面,专辑*
很可能不是属性列表对象,是吗?每个对象,一直向下,都需要是一个属性列表对象才能使其工作。 description
方法不足以实现此目的。
But the object you put inside the dictionary, an Album*
is most likely not a property list object, is it? Every object, all the way down, needs to be a property list object for this to work. A description
method isn't good enough to make this happen.
作为解决方法,您可以使用 NSCoding
和 NSKeyedArchiver
将您的字典写入 NSData
,您可以在首选项中存储。
As a workaround, you can use NSCoding
and an NSKeyedArchiver
to write out your dictionary to an NSData
, which you can store among the preferences.
这篇关于NSUserDefaults不会保存NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!