Can't figure out 'warning: incompatible Objective-C types'

后端 未结 1 493
太阳男子
太阳男子 2021-01-06 20:23

I have a subclass of NSObject that implements an -(id)initWithRootElement:(MyElement *)e method. NSXMLDocument has an identical method that takes an NSXMLEleme

相关标签:
1条回答
  • 2021-01-06 20:31

    Objective-C doesn't support covariant declarations.

    The declaration of initWithRootElement: in NSXMLDocument is as follows:

    - (id)initWithRootElement:(NSXMLElement *)element;
    

    This is different than your declaration:

    - (id)initWithRootElement:(MyElement *)element;
    

    In that the argument types are different. This causes confusion in this line of code (where element is of type MyElement *...

    [[TestClass alloc] initWithRootElement:element];
    

    ... because the return type of +alloc is id and, thus, the compiler doesn't know which method to use; which type of argument is to be expected.

    When developing code using Objective-C targeting Apple's frameworks, the rule of thumb is to never have different arguments declared for any given selector.

    I'm slightly surprised that the first case doesn't also warn. It likely should. If you have a fairly minimal test case, file a bug via http://bugreport.apple.com/ and append the bug # to this question (or my answer).

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