我正在编写一个使用NSUserDefaults作为数据存储机制的应用程序,在尝试保存数据时遇到问题(符合Property List协议):
+ (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";
}
所有注释掉的行都有相同的结果,所以我决定看看NSString“test”是否会起作用,它(当然)不会。
答案 0 :(得分:8)
但你放入字典的对象Album*
很可能不是属性列表对象,是吗?每个对象,一直向下,需要成为一个属性列表对象才能使其工作。 description
方法不足以实现这一目标。
作为一种变通方法,您可以使用NSCoding
和NSKeyedArchiver
将字典写入NSData
,您可以将其存储在偏好设置中。
答案 1 :(得分:5)
您只能将基本基础类型放入属性列表中。 NSUserDefaults将首选项写为属性列表。请参阅此处了解property list允许的类型。简而言之,它是数字,字符串,数据,日期,数组和字典。字典必须有字符串键。
答案 2 :(得分:4)
NSUserDefaults始终返回不可变对象,因此您不能将它们转换为可变对象。做[prefs objectForKey:@"my_adventure_book_albums"] mutableCopy]
(并记得在完成时释放它。)