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:

[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).


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":

SomeItemClass *item;

You could also avoid it by not declaring identically-named methods that return different types.

Need Your Help

webSql creates multiple database nodes in chrome

javascript html5 web-sql

I am lil lost here, in the Chrome development tool the DB i created is replicated multiple time.

How/Where are the environment variables in a Visual Studio C++ project set?

visual-studio visual-studio-2008 visual-c++ environment-variables

There a lots of environment variables in my project properties that I do not understand. Clicking on macros (Is there a list of Visual Studio environment variables?) gives me a list of their values...