Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Last active November 14, 2022 02:33
Show Gist options
  • Save lamprosg/5232113 to your computer and use it in GitHub Desktop.
Save lamprosg/5232113 to your computer and use it in GitHub Desktop.
(iOS) Creating custom delegates
//Class will be declared later
@class CustomClass;
//Define the protocol for the delegate
@protocol CustomClassDelegate
@required
//Required methods go here
//If there are optional functions, they go here
@optional
-(void)sayHello:(CustomClass *)customClass;
@end
//The NSObject protocol contains a method, respondsToSelector:
//that can be used to ensure the delegate object actually implements an optional method before the method is called
@interface CustomClass : NSObject
//Delegate property
@property (nonatomic, weak) IBOutlet id <CustomClassDelegate> delegate;
// define public functions
-(void)helloDelegate;
@end
#import "CustomClass.h"
@implementation CustomClass
@synthesize delegate;
-(id)init {
self = [super init];
return self;
}
//Calling this method will cause the sayHello: method to be triggered
-(void)helloDelegate {
//Verify that the delegate is set and the delegate optional method is implemented (so app won't crash)
if (delegate != nil && [delegate respondsToSelector:@selector(sayHello:)]){
[[self delegate] sayHello:self];
}
}
-(void)dealloc {
[super dealloc];
}
@end
// import our custom class
#import "CustomClass.h"
@interface ViewController : UIViewController <CustomClassDelegate>
@end
@implementation ViewController
//Initialization
- (void)viewDidLoad
{
[super viewDidLoad];
CustomClass *custom = [[CustomClass alloc] init];
//Assign delegate
custom.delegate = self;
//Calling the helloDelegate will cause the sayHello: to be triggered
[custom helloDelegate];
}
-(void)dealloc
{
[custom release];
[super dealloc];
}
//Implementing the custom delegate function
-(void)sayHello:(CustomClass *)customClass {
NSLog(@"Hiya!");
}
@end
@User2004
Copy link

User2004 commented Jan 3, 2019

Click here for set custom delegate and protocol method in swift 4.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment