Creating A Delegate Callback

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.


//You can copy the entire block below and then use find and replace on the following to make it ready for use in your application:
//MySubClassName            Sub class name within the main class
//mySubClass1               Sub class object within the main class
//MethodNameToCallBack      Main class method to be called back
//SubClassDelegate          Delegate name
In MainClass.h

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

//Add the delegate as an input to the class
@interface MainClassViewController : UIViewController
	<SubClassDelegate>
{
	MySubClassName *mySubClass1;

In MainClass.m

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

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

//********** DEALLOC **********
- (void)dealloc
{
	[mySubClass1 release];

In SubClass.h

#import <Foundation/Foundation.h>

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

@interface MySubClassName : NSObject
{
}
@property (nonatomic, assign) id  <SubClassDelegate> 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"];
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.
comments powered by Disqus
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.