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

tips & tricks

Join 7,715 other subscribers

interview questions


Algorithm Android Android Studio API APP Programming Apps AS400 blogging Browser CheatSheets Config CSS DATABASE dsa error Features GUI HTML HTML5 IDE installation Interview Questions IOS iPhone javascript Mac objective-c OneDrive OS Programming quicktips SDK SEO Settings SMO SQL swift swiftUI Teams Tips & Tricks Tools UI Web Wordpress Xcode


Archives

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from CODE t!ps

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

Continue reading