02 September 2014

Objective-c delegates

It is a long time I since I stopped working on iPhone and objc.

But some collage is working and we was discussing about objc delegates and what is it and how it is related to categories.

Following is an example illustrate how things going from Categories to Delegates.


// NSObject+TurnLights.h
// a Category on NSObject to allow any subclass to turn on/off lights
@interface NSObject (TurnLights)

-(void) turnLightsOn;
-(void) turnLightsOff;

@end

//Lights.m
// this is the lights class that delegate its work to some object (of type id) to do the on/off instead of itself
@implementation Lights

@synthesize id delegate;

-(void) doLightings{
      [delegate turnLightsOn];
      [delegate turnLightsOff];
}
@end


//MyContorller.m
// is my controller class that decided to be a delegate for the Lights class

#import "NSObject+TurnLights.h"

@implementation MyController

-(void) btnClicked:(id) sender{
      Lights* lights = ...
      [lights setDelegate: self];
}

-(void) turnLightsOn{
      NSLog("turnLightsOn");
}

-(void) turnLightsOff{
      NSLog("turnLightsOff");
}
@end

Post a Comment