5

是否可以对包含 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 自己调试呢?

4

1 回答 1

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);
}

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

于 2010-02-19T23:20:42.680 回答