How do I create delegates in Objective-C?

后端 未结 19 2565
一整个雨季
一整个雨季 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:02

    Here is a simple method to create delegates

    Create Protocol in .h file. Make sure that is defined before the protocol using @class followed by the name of the UIViewController < As the protocol I am going to use is UIViewController class>.

    Step : 1 : Create a new class Protocol named "YourViewController" which will be the subclass of UIViewController class and assign this class to the second ViewController.

    Step : 2 : Go to the "YourViewController" file and modify it as below:

    #import 
    @class YourViewController;
    
    @protocol YourViewController Delegate 
    
     @optional
    -(void)defineDelegateMethodName: (YourViewController *) controller;
    
    @required
    -(BOOL)delegateMethodReturningBool: (YourViewController *) controller;
    
      @end
      @interface YourViewController : UIViewController
    
      //Since the property for the protocol could be of any class, then it will be marked as a type of id.
    
      @property (nonatomic, weak) id< YourViewController Delegate> delegate;
    
    @end
    

    The methods defined in the protocol behavior can be controlled with @optional and @required as part of the protocol definition.

    Step : 3 : Implementation of Delegate

        #import "delegate.h"
    
       @interface YourDelegateUser ()
         
       @end
    
       @implementation YourDelegateUser
    
       - (void) variousFoo {
          YourViewController *controller = [[YourViewController alloc] init];
          controller.delegate = self;
       }
    
       -(void)defineDelegateMethodName: (YourViewController *) controller {
          // handle the delegate being called here
       }
    
       -(BOOL)delegateMethodReturningBool: (YourViewController *) controller {
          // handle the delegate being called here
          return YES;
       }
    
       @end
    

    //test whether the method has been defined before you call it

     - (void) someMethodToCallDelegate {
         if ([[self delegate] respondsToSelector:@selector(defineDelegateMethodName:)]) {
               [self.delegate delegateMethodName:self]; 
         }
      }
    

提交回复
热议问题