使用包含NSDictionary的NSMutableArray进行快速枚举

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自行调试?
1个回答

11

糟糕!arrayWithObjects:需要以nil结尾。以下代码可以正常运行:

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

我不确定为什么使用传统循环隐藏了这个错误。


啊,这是我最喜欢的C语言用语之一。“你以为运行正常的东西实际上根本不应该运行”。感谢你的初学者建议! - Alana Storm
3
如果你打开-Wformat(在Xcode中称为“Typecheck calls to printf/scanf”),编译器会对此发出警告。如果你同时打开-Werror(在Xcode中称为“Treat Warnings as Errors”),编译器会因此错误而导致编译失败。 - Peter Hosey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接