Objective-c – How to cast id to a float

castingmacosobjective-c

I'm having trouble with this code:

NSRect itemFrame;
id item;
// code to assign item goes here.
itemFrame.origin.y -= [item respondsToSelector:@selector(selectedHeight)] ? [item selectedHeight]   : [self defaultSelectedHeight];

This is the problematic bit:

[item selectedHeight]

The compiler is assuming that the return type is id. I though that adding a cast would fix this:

(float)[item selectedHeight]

but it doesn't work.

What am I doing wrong? (I suspect the problem is to do with resolving pointers related to id but I can't find any relevant documentation).

Best Solution

you want [[item selectedHeight] floatValue], assuming that the selectedHeight returns an NSNumber.