How to Create Custom Delegate

// MyViewController.h:

#import

@protocol MyProtocolName;

@interface MyViewController: UIViewController

@property (nonatomic, weak) id delegate;

@end

@protocol MyProtocolName
@required
-(void)requiredDelegateMethod;

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

@end // end of delegate protocol

In the implementation file, anytime you want to call a delegate method, first check to see if the delegate is set, and if it responds to the selector. Then call the method:

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 “MyViewController.h” // needed to include the @delegate protocol info

@interface FavoritesViewController : UIViewController


Discover more from CODE t!ps

Subscribe to get the latest posts sent to your email.

Scroll to Top

Discover more from CODE t!ps

Subscribe now to keep reading and get access to the full archive.

Continue reading