2010-02-19 27 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