Monday, July 1, 2013

Delegate in iOS

My question is "what is delegation?" after writing several iOS programs.

"Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object - the delegate - and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you easily customize the behavior of several objects in one central object."

Basically, "delegation" is way that one object communicate with the other object.

這網頁中的Example 1是一個很好的範例,講述有兩個object,為brain和beer bottle,brain可以不斷下達指令給beer bottle要喝,但是brain因為要看電視所以太忙沒有辦法知道什麼時候beer被喝完,於是乎,beer bottle此時就要用delegation,當沒有beer時告知brain。

這網頁講述了delegation中物件的關係,若此時物件A call 物件B:

  • A是B的delegate object
  • B會有A的reference
  • A會implement B的delegate method
  • B可以與A communicate,用delegate methods