【问题标题】:Enumerating over an NSMutableDictionary -- can't access object properties from within the loop枚举 NSMutableDictionary - 无法从循环内访问对象属性
【发布时间】:2011-12-09 10:00:49
【问题描述】:

我有一个 NSMutableDictionary,analyzedPxDictionary,其中包含一堆 Pixel 对象(我创建的一个自定义类)。除此之外,Pixel 对象包含一个名为rgb 的NSArray 属性。该数组将始终包含三个 NSNumber 对象,整数值对应于像素的 rgb 值。

我现在正在尝试使用快速枚举来枚举analyzedPxDictionary。但是,似乎我无法从循环中访问 Pixel 对象的属性。我已将 rgb 声明为合成属性,以便我可以使用点语法访问它。但是当我尝试在循环中这样做时,程序崩溃了,给我一个如下错误:

'-[NSCFString rgb]: unrecognized selector sent to instance 0xa90bb50'

这是产生该错误的代码示例:

for (Pixel *px in analyzedPxDictionary) {
    printf("r: %i, g: %i, b: %i",[[px.rgb objectAtIndex:0] integerValue], [[px.rgb objectAtIndex:1] integerValue], [[px.rgb objectAtIndex:2] integerValue]);
}

我已尝试在 printf 行上设置断点以检查 px。虽然 rgb 被列为一个,如果它的属性和正确描述为 NSArray 的一个实例,它似乎不包含任何对象。

我相信我正在正确初始化rgb。为了解释,请考虑以下代码:

NSString *key;
for (Pixel *px in analyzedPxDictionary) {
    key = [px description];
}

Pixel *px = [analyzedPxDictionary objectForKey:key];
printf("\nr: %i, g: %i, b: %i",[[px.rgb objectAtIndex:0] integerValue], [[px.rgb objectAtIndex:1] integerValue], [[px.rgb objectAtIndex:2] integerValue]);

这成功地将正确的值打印到控制台。

那么为什么我不能从forin 循环中访问rgb 属性?

【问题讨论】:

    标签: objective-c ios cocoa-touch for-in-loop fast-enumeration


    【解决方案1】:

    NSDictionaries 的快速枚举为您提供每个键,而不是每个值。所以你需要这样做:

    for (NSString *key in analyzedPxDictionary) 
    {
        Pixel *px = [analyzedPxDictionary objectForKey:key];
        printf("r: %i, g: %i, b: %i",[[px.rgb objectAtIndex:0] integerValue], [[px.rgb objectAtIndex:1] integerValue], [[px.rgb objectAtIndex:2] integerValue]);
    }
    

    【讨论】:

    • 谢谢。一定要喜欢简单的修复:)
    猜你喜欢
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2013-10-29
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多