Thursday, 7 February 2013

Cocoa design pattern: Delegates


delegate design pattern is a common way in IOS to communicate between different objects, it move a way from the traditional method of objects reference to communicate with them

delegates to define objects behavior

The object delegate define the behavior of the object itself.

this sentence seems to be complex at first, but take a deep look at the next example:


we have a company called "your data in table" that offer advertising services.
Hamed want to advertise in this company table, he called the company and here is the conversation

company operator: "how can i help you"
Hamed: "i stumbled upon your offer, and i have some data to show in your table"
company operator: "its pleasure to work with you, but in order to fill your data we will ask you some questions and you have to answer each one, to be able to show your data in the table"

"first question : how many rows you want to show?
second question, what will be your data for every row"

so in this short story Hamed want to communicate with the company. the company here is our OBJECT.
Hamed is the company delegate who will define the company data or on other words their table behavior.

the former story is analogues to IOS UITableView and UITableViewController object, a common way of delegates use 

UITableViewController will act as a delegate for the UITableView object.
it must implement two functions called numberOfRowInSection() and cellForRowAtSection(), these are the two questions of UITableView to UITableViewController.

whenever UITableViewController implement them, he is a valid delegate for the UITableView object. 

delegates is a notification method as well

other than define the behavior of objects, delegates often used to notify objects of something happened. 

you can find that in the main application methods like "applicationDidEnterBackground" and "applicationWillTerminate".

here delegates does not define any object behavior, it's just used to notify the main application about actions will be taken (so you can save you work or whatever process ....).

In the next post we will dig into other forms of notification similar to delegates
  • Targert/Action 
  • observers 
Salam,
M.Aleem

No comments:

Post a Comment