Clicky

iOS Dev Nugget 23 Use the Delegation Pattern

.

Need to run a code review on your codebase? Hire me

When create new classes, especially UIView and UIViewController subclasses, make use of the Delegation design pattern as much as possible to reduce dependencies. The iOS SDK makes heavy use of it so you can find examples everywhere. For example. UIAlertView has a complimentary UIAlertViewDelegate protocol and MFMailComposeViewController has a complimentary MFMailComposeViewControllerDelegate protocol. Let the caller of your custom class be the delegate by implementing it's delegation protocol. Let's say you are creating a view controller class that pops up to let the user configure some properties. The view controller might have a Done and Cancel button. It should look like:

@interface ConfigurePropertiesViewController : UIViewController

@property (nonatomic,weak) id<ConfigurePropertiesViewControllerDelegate> delegate;

@end

@protocol ConfigurePropertiesViewControllerDelegate

- (void)configurePropertiesViewController:(ConfigurePropertiesViewController*)aViewController didFinishWithInfo:(NSDictionary*)aDictionary;
- (void)configurePropertiesViewControllerDidCancel:(ConfigurePropertiesViewController*)aViewController;

@end

@implementation ConfigurePropertiesViewController

- (void)userTappedDone {
    NSDictionary* info;
    //some code to generate properties and stored into info
    [self.delegate configurePropertiesViewController:self didFinishWithInfo:info];
}

- (void)userTappedCancel {
    [self.delegate configurePropertiesViewControllerDidCancel:self];
}

//...Other code for ConfigurePropertiesViewController

@end

The calling code for ConfigurePropertiesViewController will implement ConfigurePropertiesViewControllerDelegate protocol as well as the 2 functions -configurePropertiesViewController:didFinishWithInfo: and -configurePropertiesViewControllerDidCancel:, in both functions, dismissing the view controller and in the former, make use of the data stored in the NSDictionary instance.

This helps to create clean, malleable code.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues