字典查询



我使用以下代码来检查存储在名为"myDict"的字典文件中的值为 1 或 0。在位置 'block003stored' 是值 1,在所有其他位置它是 0。如果我使用以下代码,我总是为所有位置返回 0:

for (int i = 1 ; i < 100 ; i++) {
    if(myDict)
    {
    UIImageView *imageV = (UIImageView *)[self.view viewWithTag:i];
    int myInt = [[myDict objectForKey:@"block%.3istored"] intValue];
        NSLog (@"value of i %d", i);
        NSLog (@"myInt %d", myInt);
    if (myInt == 1) imageV.hidden = FALSE;
    }
}

}

但是,如果我将对象密钥更改为专门@"block003stored":

    int myInt = [[myDict objectForKey:@"block003stored"] intValue];

我得到返回的正确值 1。我不明白为什么当我使用 %.3i 而不是 001、002、003 等时代码不起作用?

在单独的行中尝试:

NSString *indexStr = [NSString stringWithFormat:@"block%.3dstored", i]; Then use the objectForKey:indexStr];

您要求字典获取带有"block%.3istored"键的对象,该对象不存在。您需要应用格式才能使 i 进入那里。

循环中的代码使用 @"block%.3istored" 作为文字字符串。 您编写的内容中没有任何内容可以使用 i 变量格式化字符串。 将NSString的stringWithFormat:视为动态构建密钥的一种方式。

最新更新