【问题标题】:Fast Enumeration With an NSMutableArray that holds an NSDictionary使用包含 NSDictionary 的 NSMutableArray 进行快速枚举
【发布时间】:2010-02-19 23:14:08
【问题描述】:

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

【问题讨论】:

    标签: objective-c cocoa nsmutablearray nsdictionary enumeration


    【解决方案1】:

    哎呀! 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);
    }
    

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

    【讨论】:

    • 啊,我最喜欢的 Cism 之一。 “你认为正常工作的事情不应该是”。感谢新手的建议!
    • 如果开启 -Wformat(Xcode 中的“Typecheck calls to printf/scanf”),编译器会对此发出警告。如果你还开启了 -Werror(Xcode 中的“Treat Warnings as Errors”),编译器会因为这个错误导致编译失败。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    相关资源
    最近更新 更多