快速枚举使用包含NSDictionary的NSMutableArray

时间:2010-02-19 23:14:09

标签: objective-c cocoa nsmutablearray nsdictionary enumeration

是否可以对包含NSDictionary的NSArray使用快速枚举?

我正在浏览一些Objective 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);
}

应用程序在没有崩溃的情况下运行,字典输出到控制台窗口。

这是快速枚举的限制,还是我错过了一些语言的巧妙?嵌套这样的集合时还有其他陷阱吗?

对于奖励积分,我如何使用GDB自行调试?

1 个答案:

答案 0 :(得分:11)

糟糕! 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);
}

我不确定为什么使用传统循环会隐藏此错误。