views:

1024

answers:

3

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

+1  A: 

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.

Marc Charbonneau
A: 

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

e.James
+1  A: 

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.

Sherm Pendley