Objective-C: Delegates

The delegation is a commonly used pattern in object-oriented programming. It is a situation where an object, instead of performing a tasks itself, delegates that task to another, helper object. The helper object is called the delegate.

Let’s say there is a main class that wants to delegate the calculation of a sum to another class. In main class there could be a definition like this one:

DDelegateClass *myDelegate = [[DDelegateClass alloc] initWithSender:self andA:a andB:b andMethod:@selector(delegateDidCalculateSum:)];

An object called myDelegate is created with certain parameters needed to communicate between the delegate and the main object. In this example, the delegate is informed with the main class instance (self), sum parameters (a and b), and the selector to perform after the sum is calculated (delegateDidCalculateSum).

The main class defines the method called delegateDidCalculateSum which is called by the delegate after the calculation of the sum.

– (void) delegateDidCalculateSum:(NSNumber *)theSum
{
NSLog(@”The delegate calculated that %d plus %d equals %d”, a, b, [theSum intValue]);
}

Whenever the sum is calculated, this method is called.

The delegate class has a constructor defined as:

– (id) initWithSender:(id)theSender
andA:(int)intA
andB:(int)intB
andMethod:(SEL)theMethod;
{
self = [super init];
if (self != nil)
{
if ( [theSender respondsToSelector:theMethod] )
{
NSNumber *sum = [NSNumber numberWithInt:(intA + intB)];
[theSender performSelector:theMethod withObject:sum];
}
}
return self;

In the constructor, the delegate gets the parameters needed for the operation it performs. After the delegate is initialized, it checks if the main object responds to the given selector. If this is the case, the sum is calculated.

NSNumber *sum = [NSNumber numberWithInt:(intA + intB)];

When the delegate object has the information required by the main object, it performs the received selector with the sum object on the sender, i.e. main object.

[theSender performSelector:theMethod withObject:sum];