views:

80

answers:

2

Why doesn't this work?

// spriteArray is an NSMutableArray
int spriteWidth = [spriteArray objectAtIndex:0].contentSize.width;

I get the error:

Request for memeber 'contentSize' in something not a structure or union

If I change the code:

CCSprite *tempSprite = [spriteArray objectAtIndex:0];
int spriteWidth = tempSprite.contentSize.width;

Then it's okay.

I've tried casting:

int spriteWidth = (CCSprite*)[spriteArray objectAtIndex:0].contentSize.width;

But it doesn't work either.

Is there a way to do this without creating the sprite reference?

+2  A: 

I believe the . binds tighter than casting. Try

int spriteWidth = ((CCSprite*)[spriteArray objectAtIndex:0]).contentSize.width;

See this table.

David Kanarek
dreamlax beat you to it.Thanks for your help anyway!
codedeziner
I beat him by about 12 seconds, but that's ok. To see why you need to do it this way, see the table I linked to. The accessor `.` has higher precedence than casting, so the compiler tries that before changing types. To override this, you can use parentheses.
David Kanarek
Have an upvote! It's only worth two thirds of an accept, but still!
dreamlax
Thanks, I don't mind. I'm building up my score rather steadily. You can have one too.
David Kanarek
+1  A: 

The return type of objectAtIndex: is id, which is not a struct nor union. If you want to use casting, try

((CCSprite*)[spriteArray objectAtIndex:0]).contentSize.width

Otherwise, use a temporary variable.

dreamlax
Yes, that's works.I had tried placing the cast in different positions, but I didn't try the one above.Any recommendations for learning more about casting?
codedeziner