How do I create delegates in Objective-C?

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

    The approved answer is great, but if you're looking for a 1 minute answer try this:

    MyClass.h file should look like this (add delegate lines with comments!)

    #import 
    
    @class MyClass;             //define class, so protocol can see MyClass
    @protocol MyClassDelegate    //define delegate protocol
        - (void) myClassDelegateMethod: (MyClass *) sender;  //define delegate method to be implemented within another class
    @end //end protocol
    
    @interface MyClass : NSObject {
    }
    @property (nonatomic, weak) id  delegate; //define MyClassDelegate as delegate
    
    @end
    

    MyClass.m file should look like this

    #import "MyClass.h"
    @implementation MyClass 
    @synthesize delegate; //synthesise  MyClassDelegate delegate
    
    - (void) myMethodToDoStuff {
        [self.delegate myClassDelegateMethod:self]; //this will call the method implemented in your other class    
    }
    
    @end
    

    To use your delegate in another class (UIViewController called MyVC in this case) MyVC.h:

    #import "MyClass.h"
    @interface MyVC:UIViewController  { //make it a delegate for MyClassDelegate
    }
    

    MyVC.m:

    myClass.delegate = self;          //set its delegate to self somewhere
    

    Implement delegate method

    - (void) myClassDelegateMethod: (MyClass *) sender {
        NSLog(@"Delegates are great!");
    }
    

提交回复
热议问题