Dynamic typing and return values in Objective-C

后端 未结 2 1997
小鲜肉
小鲜肉 2020-12-19 17:17

I have run into a very strange behaviour I can’t make sense of. I have a Texture class with contentWidth property of type int. This cl

相关标签:
2条回答
  • 2020-12-19 18:09

    Oh well. If you are interested in why this situation happens, see the Objective-C Programming Guide, chapter 8, Return and Argument Types:

    In general, methods in different classes that have the same selector (the same name) must also share the same return and argument types. This constraint is imposed by the compiler to allow dynamic binding. Because the class of a message receiver (and therefore class-specific details about the method it’s asked to perform), can’t be known at compile time, the compiler must treat all methods with the same name alike. When it prepares information on method return and argument types for the runtime system, it creates just one method description for each method selector.

    However, when a message is sent to a statically typed object, the class of the receiver is known by the compiler. The compiler has access to class-specific information about the methods. Therefore, the message is freed from the restrictions on its return and argument types.

    Here’s a bug report in the GCC bugzilla (and a corresponding blog post). The behaviour is not a bug, but it isn’t very friendly either, because the compiler does not warn you (at least not with the default warning settings).

    0 讨论(0)
  • 2020-12-19 18:13

    Shouldn't your accessor be:

    - (int) width
    {
        return [texture contentWidth];
    }
    

    Is texture an instance variable? If it is, did you make super to initialize it in the init method or your wrapper class?

    0 讨论(0)
提交回复
热议问题