无法获得NSDictionary元素

时间:2015-10-22 11:03:29

标签: ios objective-c nsdictionary nsuserdefaults

我从NSUserDefaults获得字典词典:

NULL

这个小字典必须是NSDictionary,但是当我在循环中获取日志时,我看到了以下内容:

enter image description here

我不知道为什么,但是dict不是字典,而只是一个字符串,怎么可能从那个大字典中取字典,因为我的解决方案没有生命迹象(

dictionaryFromMemory是一本词典词典,它是以这样的方式创建和保存的:

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSData *data = [def objectForKey:keyForMemory];
NSDictionary *retrievedDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSMutableDictionary * dictionaryFromMemory = [[[NSDictionary alloc] initWithDictionary:retrievedDictionary] mutableCopy];

int flag = 0;
for (NSDictionary * dict in dictionaryFromMemory) {
    if ([[dictionary objectForKey:@"purchaseId"] isEqualToString:[dict objectForKey:@"purchaseId"]]) {
        flag = 1;
    }
}

1 个答案:

答案 0 :(得分:2)

此循环不正确:

for (NSDictionary * dict in dictionaryFromMemory) {
    if ([[dictionary objectForKey:@"purchaseId"] isEqualToString:[dict objectForKey:@"purchaseId"]]) {
        flag = 1;
    }
}
此上下文中的

dict表示迭代中的当前,因此您会看到" com.ION.PSTutorial.b.SeriesAll"。

更改循环以根据此键检索字典:

for (id key in dictionaryFromMemory) {
    NSDictionary *dict = dictionaryFromMemory[key];
    if ([dictionary[@"purchaseId"] isEqualToString:dict[@"purchaseId"]]) {
        flag = 1;
    }
}

我还冒昧地将字典访问转换为使用现代的下标语法。