代码之家  ›  专栏  ›  技术社区  ›  Alana Storm

包含nsDictionary的nsmutableArray的快速枚举

  •  5
  • Alana Storm  · 技术社区  · 15 年前

    是否可以对包含nsdictionary的nsarray使用快速枚举?

    我正在运行一些客观的C教程,下面的代码将控制台引导到gdb模式。

    NSMutableArray *myObjects = [NSMutableArray array];
    NSArray *theObjects = [NSArray arrayWithObjects:@"easy as 1",@"easy as two", @"Easy as Three"];
    NSArray *theKeys    = [NSArray arrayWithObjects:@"A",@"B",@"C"];    
    NSDictionary *theDict = [NSDictionary dictionaryWithObjects:theObjects forKeys:theKeys];
    [myObjects addObject:theDict];
    
    for(id item in myObjects)
    {
        NSLog(@"Found an Item: %@",item);
    }
    

    如果我用传统的计数循环替换快速计数循环

    int count = [myObjects count];
    for(int i=0;i<count;i++)
    {
        id item;
        item = [myObjects objectAtIndex:i];
        NSLog(@"Found an Item: %@",item);
    }
    

    应用程序运行时没有崩溃,字典输出到控制台窗口。

    这是一个快速枚举的限制,还是我遗漏了一些微妙的语言?像这样嵌套集合时还有其他的gotchas吗?

    对于奖励积分,我如何使用gdb自己调试它?

    1 回复  |  直到 15 年前
        1
  •  11
  •   andyvn22    15 年前

    哎呀! arrayWithObjects: 需要零终止。以下代码运行正常:

    NSMutableArray *myObjects = [NSMutableArray array];
    NSArray *theObjects = [NSArray arrayWithObjects:@"easy as 1",@"easy as two", @"Easy as Three",nil];
    NSArray *theKeys    = [NSArray arrayWithObjects:@"A",@"B",@"C",nil];    
    NSDictionary *theDict = [NSDictionary dictionaryWithObjects:theObjects forKeys:theKeys];
    [myObjects addObject:theDict];
    
    for(id item in myObjects)
    {
        NSLog(@"Found an Item: %@",item);
    }
    

    我不知道为什么使用传统的循环隐藏了这个错误。

    推荐文章