我想使用NSMutableDictionary實現「添加到收藏夾」功能,因爲我必須添加多個鍵值。即使在將對象添加到字典後,以下addToFavourites方法始終顯示Count = 0。我讀this並獲得nsdefaults到mutabledictionary(而不是可變數組),並將結果字典設置回nsdefaults,但不知道有什麼問題。任何幫助將非常感激。謝謝。iPhone:無法存儲到NSUserDefaults的NSMutableDictionary
編輯: 從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];
}
謝謝。
這個http://stackoverflow.com/questions/471830/why-nsuserdefaults-failed-to-save-nsmutabledictionary-in-iphone-sdk似乎是重複的。它有幫助嗎? – phi
這實際上看起來不同AppleDeveloper存儲字符串並仍然存在問題。 – Joe
@Irene:我嘗試編碼字典值,但它仍然不起作用!看到編輯的問題! – applefreak