iOS : how to create a delegate

A very simple and clear manner to explain how to create a delegate in iOS development :

Often you need a class to call back a method of its owner. In this example MainClass is the class that needs to be called back and SubClass is the class that will need to call back a method in the MainClass.

In SubClass.h

#import <Foundation/Foundation.h>

//Define the protocol for the delegate
@protocol SubClassDelegate
- (void)MethodNameToCallBack:(NSString *)s;
@end

@interface MySubClassName : NSObject
{
	id <SubClassDelegate> delegate;

}
@property (nonatomic, assign) id  delegate;  

@end
In SubClass.m

@implementation MySubClassName
//Synthesize the delegate property:
@synthesize delegate;

//When you want to callback the MainClass method:
	[[self delegate] MethodNameToCallBack:@"Hello World"];
In MainClass.h

//Include the sub class header:
#import "SubClass.h"

//Add the delegate as an input to the class
@interface MainClassViewController : UIViewController
	<SubClassDelegate>

In MainClass.m

//When the create the sub class:
	mySubClass1 = [[MySubClassName alloc] init];
	[mySubClass1 setDelegate:self];
	[mySubClass1 someMethodToGetItStartedDoingWhateverItDoes];

//The method that will be called back:
- (void)MethodNameToCallBack:(NSString *)s
{
	NSLog(s);
}

 

And the original is here.

This entry was posted in app development, iOS, iPhone, tutoriels. Bookmark the permalink.