Sunday, May 8, 2011

Delegation

On your way to developing apps you will encounter many situations when you would want to respond to certain events in your app but you would find it difficult to implement such actions in code. 

For example, you are downloading a file from the internet and you want to constantly update the progress on the screen for your user. Now to actually download stuff from the internet you would use built in classes like NSURLRequest which have been built by Apple. Now what Apple does in order for you to actually accomplish the task of showing progress is that, it tells the class NSURLRequest to send messages while it is downloading, to a class of your choice. So the NSURLRequest class is delegating tasks that it should be doing to a class of your choice. This class of your choice is known as delegate.

I guess the concept should be very clear by now, some class sends messages to some other class so that the other class may complete tasks that the first class should have done.

Let us take another example where this is used, the TableView. The TableView is used in many iOS apps including Mail and iPod. The table view has cells, and each of those cells contain data. Many a times when you tap on a cell it does some action, for ex in the iPod app when you tap on a song it starts playing it. This is done by delegation. 


So whenever a cell is tapped on a table view a message is sent to a class defined by you, let us call that class yourClass. Now what is meant by sending a message is that a predefined method specified and decided by Apple engineers is called in yourClass. In the case we are discussing, this method is tableView didSelectRowAtIndexPath is called when a cell is tapped.

You have to implement this method in yourClass and in that you can include code to take whatever action you want in response to the cell-tapping. In case of the iPod app this method will start playing the selected song.

For detailed instructions on how to include a tableView in your app refer to this post.

If you have still not got a clear idea about delegation I am very sure when you actually start delving deeper and deeper into iOS development your concepts will become clearer.


No comments: