NSDictionary长度计数错误

Jac*_*nkr 3 nsdictionary ios

{
    Items = {
        Item = {
            text = "item 1";
        }
        Item = {
            text = "item 2";
        }
        Item = {
            text = "item 3";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以上是我的NSDictionary的一个例子.请记住下一个代码段.

NSDictionary *dict = {the afore mentioned dictionary is here}
int count = [[[dict objectForKey:@"Items"] allKeys] count]; // Breakpoint here
NSLog(@"%i", count); // Breakpoint here
Run Code Online (Sandbox Code Playgroud)

在我的断点中,我得到以下值 count

  • 关于断点1 :( count = (int) 128037184或其他一些随机和大的int)
  • 在断点2: count = (int) 5

我原本预计会有3次int.这是怎么回事?

Cal*_*leb 12

在第一种情况下,您在执行该行之前count就已断开,因此将在堆栈中的该位置发生任何随机数据.如果您在调试器中跳过该指令,您将看到count更改为更合理的数字.

在第二种情况下,我不确定为什么你有比你想象的更多的键,但简单的做法是只记录整个字典,看看有什么:

NSLog(@"%@", dict);
Run Code Online (Sandbox Code Playgroud)

这将显示字典中的所有键和值,这可以解释您获得的数字.

  • 还要注意:当你停在一条线上时,它还没有被执行 (3认同)

gan*_*esh 5

我使用[dict count]来计算NSDictionary中的对象数.