1

Possible Duplicate:
How does a delegate work in objective-C?

Hello Community,

I have been trying to understand the concept of delegates in Objective-C. I tried following up the documentation, however I am looking for some really easy example to get familiarized as of how to send messages between delegates and if I want to create a custom delegate, how may I go further with that?

Hope someone could make me better understand this concept.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Shawn Sngh
  • 51
  • 1
  • 1
  • 4

2 Answers2

1

The basic concept of delegates is to delegate important decisions or information to some other object instance.

In most frameworks you use subclassing and override methods in order to hook into the application flow. It works but the drawbacks are many, for example:

  • You can not change the decision maker without a complete new subclass.
  • Without multiple inheritance you can only make decisions for one object (yourself).

There are four reasons why an object might want to call upon a delegate, and each of these four uses a keyword in the delegate method name to signal this. It's a naming convention only, but you should follow the pattern if you want to be a good citizen.

  • Ask if something should happen. For example: gestureRecognizer:shouldReceiveTouch:
  • Before something unavoidable is going to happen. For example: applicationWillTerminate:.
  • After something has occured. For example: accelerometer:didAccelerate:
  • And to retrieve data, this is more a data source than a delegate, but the line between the two are fuzzy. The name do not contain a defined name, but should contain the named piece of data that is requested. For example: tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:

As a general rule the first argument to any delegate method should be the named object instance requesting delegation.

PeyloW
  • 36,742
  • 12
  • 80
  • 99
  • PeyloW, the four reasons you have provided, these won't be the only reason's why delegate must be call upon right? Maybe the prime reason's I would say. Like, can't we also call delegate when going to "BackGround", also are there any really easy examples to follow just a quick NSLog method to get an update once something have done, via delegate? – Shawn Sngh May 10 '11 at 17:28
  • Well for background stuff I still think the four rules applies, if `Foo` can be *backgrounded*, then you probably have one or more of these: `shouldFooEnterBackground:`, `fooWillEnterBackground:`, `fooDidEnterBackground:`, and/or `tokenForEnteringBackgroundWithFoo:`. Apple has a sample app named PhotoPicker that is a good starting point, it both uses delegates from UIKit, and define/use a delegate of it's own, all in only two small classes: http://developer.apple.com/library/ios/#samplecode/PhotoPicker/ – PeyloW May 10 '11 at 18:06