Objective-C: Another article on Using custom delegates

Using custom delegates in Objective-C

01 Aug 2009

 

On Stack Overflow there has been some interest in how to use the Delegate design pattern in Objective-C. Of course, the first step in any search should be to read Apple’s documentation, but many people seem not to want to read the whole thing. Trust me, folks, it is worth it. But Apple’s documentation on creating delegates doesn’t use protocols, which are such an amazing and useful part of the Objective-C language.

 

That being said, I’d like to give a short demonstration of how to create a class with a delegate. For the purposes of this tutorial, we’ll call our class JSTutorial.

The interface to JSTutorial starts out as the following:

@interface JSTutorial: NSObject {

  NSString *title;

  NSString *body;

}

- (void)generateTutorial;

@property (nonatomic, retain) NSString *title;

@property (nonatomic, retain) NSString *body;

 

@end

 

Now, we need to modify this interface to include a delegate protocol:

 

@class JSTutorial;

@protocol JSTutorialDelegate <NSObject>

@optional

- (void)tutorialDidFinish:(JSTutorial *)tutorial;

@end

 

@interface JSTutorial: NSObject {

  NSString *title;

  NSString *body;

  id <JSTutorialDelegate> delegate;

}

 

- (void)generateTutorial;

@property (nonatomic, retain) NSString *title;

@property (nonatomic, retain) NSString *body;

@property (nonatomic, assign) id <JSTutorialDelegate> delegate;

 

@end

 

The implementation for JSTutorial might look like this:

 

@implementation JSTutorial

@synthesize title;

@synthesize body;

@synthesize delegate;

 

- (void)generateTutorial {

  // do something here?

  [[self delegate] tutorialDidFinish:self];

}

 

- (void)dealloc {

  [title release];

  [body release];

  [super dealloc];

}

 

@end

 

Finally, the class that implements JSTutorialDelegate might have its interface declared as follows:

 

 

@interface SomeClass : SomeControllerClass <JSTutorialDelegate>

...

@end

SomeClass should implement tutorialDidFinish:, but it is optional.

I hope that this has helped those who were struggling with the delegate design pattern.

 

 

An article by Jonathan Sterling

Advertisements
This entry was posted in General and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s