Create your own Objective-C Delegate Protocol


 

 

 

To create your own custom delegate protocol, you need to modify the header file 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.

// 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 iOS if Statement:

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:

#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

// 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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: