iPhone:无法将NSMutableDictionary存储到NSUserDefaults

时间:2011-07-06 14:37:41

标签: iphone nsuserdefaults nsmutabledictionary

我正在尝试使用NSMutableDictionary实现“添加到收藏夹”功能,因为我必须添加多个键值。即使将对象添加到字典后,以下addToFavourites方法也始终显示Count = 0。我读了this并将nsdefaults变成了mutabledictionary(而不是mutable数组),并将结果字典设置回nsdefaults,但不确定是什么问题。任何帮助将非常感激。谢谢。

编辑:    从this我开始知道我必须在可变和不可变的字典周围移动数据然后它工作正常!但仍然无法将修改后的NSMutableDictionary与NSUserDefaults同步。

-(BOOL)isAddedToFavorites:(NSString*)viewID {
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *favourites = [[standardUserDefaults objectForKey:kFavouriteItemsKey] mutableCopy];

if(favourites && [[favourites objectForKey:kFavouriteItemsKey] objectForKey:viewID])
return YES;

return NO;
}

-(void)addToFavourites:(NSString*)viewID viewType:(NSString*)viewType {
NSMutableDictionary *myMutableDictionary= [NSMutableDictionary dictionaryWithCapacity:[myDictionary count]+1];
[myMutableDictionary addEntriesFromDictionary:myDictionary];
[myMutableDictionary setObject:myObject forKey:myKey];


// Modified dictionary is not getting synced
[[NSUserDefaults standardUserDefaults]  setObject:myMutableDictionary  forKey:kFavouriteItemsKey];
[[NSUserDefaults standardUserDefaults]  synchronize];
}

尝试将字典数据编码到NSData,现在它经过了轻微但严重的修正后才能正常工作!

-(BOOL)isAddedToFavorites:(NSString*)viewID {

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:kFavouriteItemsKey];
NSDictionary *favourites = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 

if(favourites && [favourites objectForKey:viewID])
    return YES;

return NO;
}

-(void)addToFavourites:(NSString*)viewID viewType:(NSString*)viewType {

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:kFavouriteItemsKey];
NSDictionary *myDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 

NSMutableDictionary *myMutableDictionary= [NSMutableDictionary dictionaryWithCapacity:[myDictionary count]+1];
[myMutableDictionary addEntriesFromDictionary:myDictionary];
[myMutableDictionary setObject:viewType forKey:viewID];


NSData *newdata = [NSKeyedArchiver archivedDataWithRootObject:myMutableDictionary];
[[NSUserDefaults standardUserDefaults] setObject:newdata forKey:kFavouriteItemsKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}

感谢。

1 个答案:

答案 0 :(得分:2)

您需要为字典中的元素实现此功能:

字典中的元素实现

@interface CommentItem : NSObject<NSCoding> {
    NSString *value;
}

然后在CommentItem的实现中,提供了两种方法:

-(void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:value forKey:@"Value"];
}

-(id)initWithCoder:(NSCoder *)decoder
{
    self.value = [decoder decodeObjectForKey:@"Value"];
    return self;
}

正如@Irene提供的链接所示。