To create your own custom delegate protocol, you need to modify the header file (.h) for the selected class to then add the @protocol declaration, a delegate @property, and declare the methods that delegates can implement:

Please note; this tutorial is written on the understanding that you have basic to moderate knowledge in the iOS Application Development language: Objective-C. If this is not the case then I suggest that you read Beginners Guide to Objective-C for Developers to further develop your knowledge and ensure you can successfully follow on with this tutorial.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// YourViewController.h:

#import <UIKit/UIKit.h>

@protocol YourProtocolName

@interface YourViewController: UIViewController

@property (nonatomic, weak) id<YourProtocolName> delegate;

@end

@protocol YourProtocolName <NSObject>
@required
-(void)requiredDelegateMethod;

@optional
-(void)optionalDelegateMethodOne;
-(void)optionalDelegateMethodTwo:(NSString *)withArgument;

@end // end of delegate protocol

Next, In the implementation file, anytime you want to call the delegate method, you first need to check and see if the delegate is set, and then if it responds to the selector. Once this is checked, then you can call the method, for this we are going to use an Objective-C if Statement:


1
2
3
if (self.delegate && [self.delegate respondsToSelector:@selector(optionalDelegateMethodOne)]) {
    [self.delegate optionalDelegateMethodOne];
}

Now for classes you want to conform to your new protocol, include the header file and delegate protocol in the @interface:


1
2
3
#include "YourViewController.h"  // needed to include the @delegate protocol info

@interface FavoritesViewController : UIViewController <YourProtocolName>

Finally, any required delegate methods must then be implemented in your class’s @implementation file.

Update from reddit user brainotomy:

I thought it worth while to explain that the first @protocol line in the header is only needed if the actual protocol comes after the @interface@end code.
So this works as well


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// YourViewController.h:

 #import <UIKit/UIKit.h>

 @protocol YourProtocolName <NSObject>
 @required
 -(void)requiredDelegateMethod;

 @optional
 -(void)optionalDelegateMethodOne;
 -(void)optionalDelegateMethodTwo:(NSString *)withArgument;

 @end // end of delegate protocol

 @interface YourViewController: UIViewController

 @property (nonatomic, weak) id<YourProtocolName> delegate;  

 @end

Enjoyed this post?

Subscribe to our RSS Feed or Follow us on twitter to keep up to date with the latest from iOS-Blog. Remember, Sharing is caring so please click one of the following options:

Tags: , , , ,