我遇到了一个奇怪的问题,将 an 存储NSDictionary
到 theNSUserDefaults
然后检索它会将其转换为NSCFString
.
这是我保存数据的地方:
- (void)saveProgress
{
// Save our progress to the user defaults.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *progressDict = [NSMutableDictionary dictionary];
if ([defaults objectForKey:@"session_progress"] != nil) {
[progressDict addEntriesFromDictionary:[defaults dictionaryForKey:@"session_progress"]];
}
NSMutableDictionary *targetsDict = [NSMutableDictionary dictionary];
if ([progressDict objectForKey:@"targets"] != nil) {
[targetsDict addEntriesFromDictionary:[progressDict objectForKey:@"targets"]];
}
NSMutableDictionary *trackableDict = [NSMutableDictionary dictionary];
if ([targetsDict objectForKey:@"mda_sao_ext_04"]) {
[trackableDict addEntriesFromDictionary:[targetsDict objectForKey:@"mda_sao_ext_04"]];
}
[trackableDict setObject:[NSNumber numberWithBool:YES]
forKey:@"viewed"];
NSLog(@"SAVE Trackable %@ %@", [trackableDict class], trackableDict);
[targetsDict setObject:trackableDict
forKey:@"mda_sao_ext_04"];
NSLog(@"SAVE Targets %@ %@", [targetsDict class], targetsDict);
[progressDict setObject:targetsDict
forKey:@"targets"];
[defaults setObject:progressDict
forKey:@"session_progress"];
[defaults synchronize];
}
这是我加载数据的地方:
- (NSInteger)loadProgress
{
// Load our progress from the user defaults.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"session_progress"] == nil) {
return 0;
}
NSDictionary *progressDict = [defaults dictionaryForKey:@"session_progress"];
if ([progressDict objectForKey:@"targets"] == nil) {
return 0;
}
NSDictionary *targetsDict = [progressDict objectForKey:@"targets"];
NSLog(@"LOAD Targets %@ %@", [targetsDict class], targetsDict);
NSInteger viewedCount = 0;
for (NSDictionary *trackableDict in targetsDict) {
NSLog(@"LOAD Trackable %@ %@", [trackableDict class], trackableDict);
if ([[trackableDict objectForKey:@"viewed"] boolValue]) {
++viewedCount;
}
}
return viewedCount;
}
该应用程序在loadProgress
. 这是控制台的输出:
LOAD Targets __NSCFDictionary {
"mda_sao_ext_04" = {
scanned = 1;
viewed = 1;
};
}
LOAD Trackable __NSCFString mda_sao_ext_04
您可以从第一个跟踪中看到 `mda_sao_ext_04 是一个字典,但由于某种原因它被转换为一个字符串。
有什么想法或建议吗?谢谢!