HOW TO CAST ID INTO A FLOAT?

Tarun Kumar

Total Post:214

Points:1642
Posted by  Tarun Kumar
 707  View(s)
Ratings:
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.

  1. Nigel Bunyan

    Post:20

    Points:140
    Re: How to cast id into a float?

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!