How do I cast id to a float?
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:
The compiler is assuming that the return type is id. I though that adding a cast would fix this:
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).
you want [[item selectedHeight] floatValue], assuming that the selectedHeight returns an NSNumber.
I know that below code works for iOS 6 SDK. I assume that obj object contains a float value.
id obj; float fVal; fVal = [obj floatValue];
You need to look at the declaration of your selectedHeight method. The problem is either that the method is returning a pointer to an object (id), or you haven't imported the header file for item in the file that contains the code snippet, so Xcode assumes it's a pointer by default.
You can't cast a pointer to a float, since they're fundamentally incompatible types. Once you get your declarations straightened out though you should be okay.
The compiler makes that kind of assumptions when multiple classes declare methods with the same name, that return different types. Since your "item" variable is typed as an "id," the compiler doesn't know which of these classes it will be sending the message to at run time, and chooses one.
To avoid this problem, you can inform the compiler what class "item" is an instance of, by declaring it with a specific type instead of the generic "id":
You could also avoid it by not declaring identically-named methods that return different types.