I'm just trying to save a dictionary of dictionary of array in NSUserdefaults without success. Here is my code:
+ (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];
}
When I run the app the first time, it saves the data properly which means the yearData
will contain one month but after adding more data to that array I can't find them when calling userHasAlreadyLoad; I can just see one month for the same territoryId and Year which is the first month I added. Anything I missed here?
When you get dictOfTerritory
, you call mutableCopy
on it, which gets you a copy of that dictionary. And you only save value to that copied dictionary, not the one that has reference in the main dict
dictionary.
Try the following code where you're saving dictionaries.
dictOfTerritory[[@(year) stringValue]] = yearData;
[dict setObject:dictOfTerritory forKey:[territoryId stringValue]];
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:USER_SETTING_MONTHS_LOADED];