max*_*son 3 cocoa-touch objective-c fast-enumeration for-in-loop ios
我有一个NSMutableDictionary,analyzedPxDictionary包含一堆Pixel对象(我创建的自定义类).除此之外,Pixel对象包含一个名为NSArray的属性rgb.该数组将始终包含三个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]);
}
Run Code Online (Sandbox Code Playgroud)
我试过在那条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]);
Run Code Online (Sandbox Code Playgroud)
这会成功将正确的值打印到控制台.
那么为什么我不能rgb从forin循环中访问属性呢?
快速枚举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]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
258 次 |
| 最近记录: |