gpt4 book ai didi

iPhone:无法将 NSMutableDictionary 存储到 NSUserDefaults

转载 作者:行者123 更新时间:2023-12-03 21:06:31 26 4
gpt4 key购买 nike

我正在尝试使用 NSMutableDictionary 实现“添加到收藏夹”功能,因为我必须添加多个键值。即使将对象添加到字典后,以下 addToFavourites 方法也始终显示 Count=0。我读过this并将 nsdefaults 放入可变字典(而不是可变数组)并将结果字典设置回 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];
}

谢谢。

最佳答案

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

字典中的元素实现

@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 提供的链接上的建议。

关于iPhone:无法将 NSMutableDictionary 存储到 NSUserDefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6598198/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com