2010-02-19 59 views
5

可以使用包含NSDictionary的NSArray使用快速枚举吗?使用包含NSDictionary的NSMutableArray快速枚举

我通过一些目标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自己调试呢?

回答

10

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

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

+0

啊,我最喜欢的Cisms之一。 “你认为工作正常的东西不应该是”。感谢新手的建议! – 2010-02-19 23:54:18

+3

如果您打开-Wformat(Xcode中的“Typecheck调用printf/scanf”),编译器会警告这一点。如果你也打开-Werror(Xcode中的“将警告视为错误”),则编译器将因此错误而编译失败。 – 2010-02-20 07:09:33

+0

谢谢彼得,非常有用! – 2010-02-20 18:43:52