Thursday, February 28, 2013

Communication Between MVC Controllers

When there are more than two MVC controllers, controllers need to pass data or send notifications between two controllers. For example, a table list controller, parent, may push to an item edit controller, child, when an item is selected. The easiest way to is to set a property in child controller and pass the reference to parent controller to child's property. However, this strategy has one drawback: strong binding between parent and child controllers. In case the parent controller is changed to another kind of controller, the property of child has to be updated.

The alternative way is to implement delegate in Objective-C. Define a delegate in .h, then keep communication by defined methods in the delegate. Here is the steps of this strategy.

Define a Delegate

The delegate provides APIs to pass data or to send notifications. For example, the following codes define a update method:

@protocol MyEntityEditDelegate <NSObject>

- (void) updateEntity:(NSIndexPath *)index;

@end

Add a Delegate Property in Parent Controller

The next step is to implement the delegate property in the parent controller. This breaks the strong binding between the parent and child. The child will call parent by the delegate APIs.


@interface ParentListViewController :
    UITableViewController <..., MyEntityEditDelegate>

....
@end

Define a Delegate Property in Child Controller

The last step is to add delegate property in the child controller. This will let the child hold a reference to its parent by delegate.

@interface ChildEntityEditViewController : ...

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

@end

Notice that the property type is id<...> type. This prevents the coupling between the parent and child.

0 comments: