How to conform to a self-made protocol?

后端 未结 7 1759
忘了有多久
忘了有多久 2021-02-10 16:33

I have a class with an delegate property. Anyone who wants to be a delegate must conform to a protocol. I defined everything like this:

#import 

        
相关标签:
7条回答
  • 2021-02-10 17:11

    I think you need to #import the header file that defines the protocol. How can the compiler know which methods are available without it?

    If you use another class (i.e., as an ivar or as a parameter to a method) then you can use a forward declaration. But if you subclass then you need to #import.

    0 讨论(0)
  • Put the definition of the protocol in a separate file.

    #import that file into any header file that needs it.

    0 讨论(0)
  • 2021-02-10 17:19

    Your two classes differ in their use of the protocol. MyClass does not implement the protocol, it has an attibute that is a pointer to a class that implements the protocol. OtherClass should implement the protocol.

    OtherClass needs to have available before its interface is defined all the details of the protocols, interfaces and classes that it inherits from. Thus you need the protocol in a header to be #imported in OtherClass.h

    MyClass just needs to know the protocol exists in its interface.

    Note on Stephen's reply subclassing is the case you can't use forward declarations of classes. (In the example OtherClass is a subclass of NSObject)

    0 讨论(0)
  • 2021-02-10 17:30

    Also see Apple's Communicating with Objects, which discusses delegates, protocols, and selectors.

    0 讨论(0)
  • 2021-02-10 17:31

    The compiler's warning is correct. OtherClass doesn't conform to the protocol because it doesn't declare the required fooBarWithFoo method that the protocol expects.

    Have you tried it this way?

    #import "MyClass.h"
    
    @interface OtherClass : NSObject <TheDelegateProtocol> {
        // ivars
    }
    
    - (void)fooBarWithFoo:(CGFloat)foo; // <<< missing bit
    
    @end
    
    0 讨论(0)
  • 2021-02-10 17:32

    He doesn't need to declare the methods to conform to the protocol. He only need to implement them in the .m file.

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