How to cast id into a float?

Total Post:214


 1221  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 amoing wrong.oing wrong. I doing wrong.

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

      Modified On Apr-10-2018 02:45:17 AM


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.