Using custom delegates in Objective-C
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:
@protocol JSTutorialDelegate;@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
@protocol JSTutorialDelegate <NSObject>@optional- (void)tutorialDidFinish:(JSTutorial *)tutorial;@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.
Comments
Post a Comment