Using Protocols and Delegates to pass data between views

It’s a common pattern to have a form where the user needs to choose some option, when he clicks in one of the options, it redirects to another view where he can choose¬†between¬†many options. After selecting the correct options you usually want to redirect your user to the previous view with the selected data in place. A common way of doing this is defining a formal protocol.

Understanding correctly how to use delegates in iphone programming is key to achieve clean code. A delegate is a helper object which is used by another object that instead of performing some action it “passes the bucket” to another object, the delegate. This is called “inversion of responsability or dependency inversion“. This is a common abstraction pattern called delegation.

Protocols are vary similar to Java interfaces. They difference is that a class may implement a protocol without declaring that it implements it. At Wikipedia you can read a more in depth explanation of the concept of protocols.

There are a couple of texts like this one that describes a singleton solution to “Passing simple data between views“, in a sense it’s a way of using global variables to share data among all the parts of the application. From a OOP perspective it’s strange, because it gives access to every object on the application to alter these variables.

This question on stack overflow points to three possible solutions: setting a member variable in the child, when it’s passed to the parent, send a message to [self superview] and use a NSNotification.

One interesting thread where auditors of CS 193P iphone application development course on stanford discuss the correct way (from an architecture standpoint) of passing values between views. According to these guys, you should never use the application delegate neither global variables, and point to using delegation.

Apple has a very extensive explanation about the concept of protocols in their developer website.

The Core Data Books example app from apple has a very good implementation of protocols in DetailViewController.m

Leave a Reply