0

I am a beginner so I need a simple example of custom delegates. How we can create, use and call? Step by step explanation would be appreciated. i know that the question asked many times before but still confused.
Thanks in advance.

  • There is nothing magical about a delegate. It's just an object whose address you pass to some other object (such as a table view) which may need information later. When the other object needs information it calls methods of the first, "delegate" object to get that info. Usually the interface to the delegate is defined by a "protocol" rather than a class interface, but that's a convenience, not critical to the concept. – Hot Licks Apr 01 '14 at 01:10

1 Answers1

0

A delegate is little more than a property or ivar to another object that may be called to perform specific methods. Normally, a Protocol is created defining optional and required method declarations for this delegate object and the delegate object implements at least the required ones.

This API contract ensures you can rely on delegating some business logic to the delegate object. Your object does not need to know how the delegate will make decisions. It just sends messages to the delegate and can rely on the results if any are returned.

The delegate does not need to know the precise object it is delegating for unless the method includes it as an argument.

The idea is that the delegate can know things the other object doesn't ever need to know about.

Essentially it makes delegates tend to be controller classes but not always.

It enables objects such as views and controls to be generic and reusable.

It also enables event driven programs with ideas like "hey delegate should I do this now?" Or "hey delegate what kind of thing should I display? X, Y or Z?" Or "delegate give me an object that makes sense to you under ABC criteria"

NSMenuDelegate is a great example NSApplicatonDelegate and UIApplicationDelegate are great examples.

NSTableView and UITableView (and other collection views) also give great delegate examples. They also show how this pattern can have other names containing things like "DataSource" for doing more specific things like providing data for the collection.

uchuugaka
  • 12,679
  • 6
  • 37
  • 55