How do I create delegates in Objective-C?

后端 未结 19 2531
一整个雨季
一整个雨季 2020-11-21 04:48

I know how delegates work, and I know how I can use them.

But how do I create them?

19条回答
  •  梦谈多话
    2020-11-21 05:10

    As a good practice recommended by Apple, it's good for the delegate (which is a protocol, by definition), to conform to NSObject protocol.

    @protocol MyDelegate 
        ...
    @end
    

    & to create optional methods within your delegate (i.e. methods which need not necessarily be implemented), you can use the @optional annotation like this :

    @protocol MyDelegate 
        ...
        ...
          // Declaration for Methods that 'must' be implemented'
        ...
        ...
        @optional
        ...
          // Declaration for Methods that 'need not necessarily' be implemented by the class conforming to your delegate
        ...
    @end
    

    So when using methods that you have specified as optional, you need to (in your class) check with respondsToSelector if the view (that is conforming to your delegate) has actually implemented your optional method(s) or not.

提交回复
热议问题