How to create a delegate in Objective-C?

Keywords: iOS Programming Java

I know how delegates work and I know how to use them.

But how do I create it?

#1st floor

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

MyClass.h file should look like this (add annotated delegate line!)

#import <BlaClass/BlaClass.h>

@class MyClass;             //define class, so protocol can see MyClass
@protocol MyClassDelegate <NSObject>   //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 <MyClassDelegate> delegate; //define MyClassDelegate as delegate

@end

The 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 this case called MyVC's UIViewController) MyVC.h in another class:

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

MyVC.m:

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

Implementation delegation method

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

#2nd floor

Please! Check out the following simple step-by-step tutorial to learn how Delegates works in iOS.

Represented in iOS

I created two ViewControllers (for sending data from one to another)

  1. FirstViewController implements delegation (provides data).
  2. The SecondViewController declares a delegate (which will receive data).

#3rd floor

I think once you understand the representation, all of these answers make sense. Personally, I come from the programming languages before C / C + +, such as Fortran, etc., so this is 2 minutes for me to look for similar things in the C + + example.

If I want to explain delegates to C ++ / Java programmers, I will say

What are the delegates? These are static pointers to classes in another class. After you assign a pointer, you can call functions / methods in the class. As a result, some functions of your class are "delegated" (in the C + + world - pointed to by a class object pointer) to another class.

What is an agreement? Conceptually, it works like a header file for a class that you specify as a delegate class. The protocol is an explicit method that defines which method pointers need to be implemented in the class to be set as delegates in the class.

How can I do similar things in C + +? If you try to do this in C + +, you can define pointers to classes (objects) in the class definition and then connect them to other classes that provide other functions as delegates to the base class. But this kind of wiring needs to be kept in the code, and it will be clumsy and error prone. Objective C assumes that the programmer is not good at maintaining the decision and provides compiler constraints to enforce clean implementation.

#4th floor

Well, that's not the real answer, but if you're looking for ways to make your own representation, something simpler might be a better answer.

It's hard for me to achieve my representation because I rarely need it. I can only have one delegate for a delegate object. So it's better if you want your representatives to communicate / pass data in a one-way way way, rather than through notifications.

NSNotification can deliver objects to multiple recipients, and it's very easy to use. Its working principle is as follows:

The MyClass.m file should look like this

#import "MyClass.h"
@implementation MyClass 

- (void) myMethodToDoStuff {
//this will post a notification with myClassData (NSArray in this case)  in its userInfo dict and self as an object
[[NSNotificationCenter defaultCenter] postNotificationName:@"myClassUpdatedData"
                                                    object:self
                                                  userInfo:[NSDictionary dictionaryWithObject:selectedLocation[@"myClassData"] forKey:@"myClassData"]];
}
@end

To use your notification in another class: add the class as an observer:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(otherClassUpdatedItsData:) name:@"myClassUpdatedData" object:nil];

Implementation selector:

- (void) otherClassUpdatedItsData:(NSNotification *)note {
    NSLog(@"*** Other class updated its data ***");
    MyClass *otherClass = [note object];  //the object itself, you can call back any selector if you want
    NSArray *otherClassData = [note userInfo][@"myClassData"]; //get myClass data object and do whatever you want with it
}

If so, don't forget to delete your class as an observer

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#5th floor

As a good practice recommended by Apple, it's useful to represent (by definition, it's a protocol) compliance with the NSObject protocol.

@protocol MyDelegate <NSObject>
    ...
@end

& create an optional method in your delegate (that is, a method that does not necessarily need to be implemented), you can use the @ optional annotation as follows:

@protocol MyDelegate <NSObject>
    ...
    ...
      // 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

Therefore, when you use a method that has been specified as optional, you need to check (in your class) the respondsToSelector if the view (that matches your delegate) actually implements your optional method.

Posted by legacyblade on Sat, 21 Dec 2019 07:14:10 -0800