Reputation: 17553
I have an NSMutableDictionary, analyzedPxDictionary
, containing a bunch of Pixel objects (a custom class I created). Among other things, Pixel objects contain an NSArray property called rgb
. That array will always contain three NSNumber objects, with integer values corresponding to the pixel's rgb values.
I'm now trying to enumerate over the analyzedPxDictionary
using fast enumeration. However, It seems like I'm not able to access Pixel objects' properties from within the loop. I have declared rgb
to be a synthesized property so that I can access it using dot syntax. But when I try to do so from within the loop, the program crashes, giving me an error like the following:
'-[NSCFString rgb]: unrecognized selector sent to instance 0xa90bb50'
Here's an example of the code that produces that error:
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]);
}
I've tried setting a break point on that printf
line in order to inspect px
. While rgb
is listed as one if its properties and correctly described as an instance of NSArray, it doesn't seem to contain any objects.
I believe that I'm initializing rgb
correctly. To explain, consider the following code:
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]);
This successfully prints the correct values to the console.
So why can't I access the rgb
property from within the forin
loop?
Upvotes: 3
Views: 273
Reputation: 119242
Fast enumeration of NSDictionaries gives you each key, not each value. So you'd need to do:
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]);
}
Upvotes: 6