Home > DeveloperSection > Forums > How to cast id into a float?
Tarun Kumar

Total Post:213

Points:1635
Posted on    September-22-2015 11:55 PM

 iPhone iPhone  Ios  Objective C 
Ratings:


 1 Reply(s)
 450  View(s)
Rate this:

I write a code and getting problem with this code:

NSRect myFrame;

id item;

// for assigning code to item

myFrame.origin.y -= [item respondsToSelector:@selector(myHeight)] ? [item myHeight]   : [self defaultMyHeight];

Here is the problem:

[item myHeight]

The compiler is assuming that the return type is id. So, I thought that by using type cast I would fix this:

(float)[item myHeight]

 

but it’s not working.

So, I’m not understanding that what am I doing wrong.



Nigel Bunyan
Nigel Bunyan

Total Post:20

Points:140
Posted on    September-23-2015 2:23 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick