0

我只是想在 NSUserdefaults 中保存数组字典的字典,但没有成功。这是我的代码:

+ (BOOL) userHasAlreadyLoad:(NSNumber *)territoryId year:(NSInteger)year month:(NSInteger)month
{
    NSMutableDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:USER_SETTING_MONTHS_LOADED];
    NSMutableDictionary *dictOfTerritory = dict[[territoryId stringValue]];
    if (dictOfTerritory == nil)
        return NO;

    NSMutableArray *yearData = dictOfTerritory[[@(year) stringValue]];
    if (yearData == nil)
        return NO;

    if ([yearData containsObject:@(month)])
        return YES;
    return NO;
}

+ (void) setUserLoad:(NSNumber *)territoryId year:(NSInteger)year month:(NSInteger)month
{
    NSMutableDictionary *dict = [[[NSUserDefaults standardUserDefaults] objectForKey:USER_SETTING_MONTHS_LOADED] mutableCopy];
    NSMutableDictionary *dictOfTerritory = [dict[[territoryId stringValue]] mutableCopy];
    if (dictOfTerritory == nil)
    {
        dictOfTerritory = [NSMutableDictionary dictionary];
        dict[[territoryId stringValue]] = dictOfTerritory;
    }
    NSMutableArray *yearData = [dictOfTerritory[[@(year) stringValue]] mutableCopy];
    if (yearData == nil)
    {
        yearData  = [NSMutableArray array];
    }
    if (![yearData containsObject:@(month)])
    {
        [yearData addObject:@(month)];
    }
    dictOfTerritory[[@(year) stringValue]] = yearData;
    [[NSUserDefaults standardUserDefaults] setObject:dict forKey:USER_SETTING_MONTHS_LOADED];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

当我第一次运行应用程序时,它会正确保存数据,这意味着yearData它将包含一个月,但是在向该数组添加更多数据后,我在调用 userHasAlreadyLoad 时找不到它们;我只能看到同一区域 ID 和年份的一个月,这是我添加的第一个月。我在这里错过了什么?

4

1 回答 1

0

当你得到 时dictOfTerritory,你调用mutableCopy它,它会得到那个字典的副本。而且您只将值保存到复制的字典中,而不是在主字典中引用的dict字典。

在保存字典的位置尝试以下代码。

    dictOfTerritory[[@(year) stringValue]] = yearData;
[dict setObject:dictOfTerritory forKey:[territoryId stringValue]];
    [[NSUserDefaults standardUserDefaults] setObject:dict forKey:USER_SETTING_MONTHS_LOADED];
于 2015-09-13T18:40:37.577 回答