iOS delegates from Java Developers POV

Go To StackoverFlow.com

4

I've been a Java Developer for several years and about a year ago moved onto Android development. After tackling Android, I then attempted to test my luck with iOS. So far so good, but I'm still very hazy on the ideas of "Delegates." I've read several articles on here and still don't have the best idea on them. To me, they seem similar to Inheritance in Java, such as using an interface or an abstract class.

Can anyone clarify in a view that I may understand?

Thanks in Advance.

2012-04-05 16:47
by Agent 404


10

No, that's not the same concept of inheritance.

I would say that it's like the listener approach used in AWT/Swing. Eg:

class MyActionListener implements ActionListener {
  public void actionPerformed(ActionEvent e) { ... }
}

myComponent.addActionListener(new MyActionListener);

This with a delegate approach in ObjC would look like:

@class MyActionListener : NSObject<NSActionListener>

-(void) actionPerformed:(NSEvent*)event;

@end

myComponent.delegate = [[[MyActionListener alloc] init] autorelease];

In practice you delegate some of the behavior of a class to a specific other object used by composition (and NOT by inheritance) so that the delegate methods will be called when needed (either for callback, either to provide specific implementations and whatever)

2012-04-05 16:52
by Jack
This is a great explanation. You said it way better than I did - PRNDL Development Studios 2012-04-05 16:54
This solves my problem :) Thank you. I'll accept as Answer in just a moment - Agent 404 2012-04-05 16:56
+1 very informative.. - Samir Mangroliya 2012-07-30 10:15


1

When using an object, you can inherit some callback methods from its class. Basically, you can respond when that object has an event.

The object class is "delegating" that event to your class instance.

2012-04-05 16:50
by PRNDL Development Studios
So basically, I'm intercepting the call to the pre-defined method of that class, and it's going to my custom code instead - Agent 404 2012-04-05 16:51
As I understand it, yes. You are becoming the event handler, instead of that object's class - PRNDL Development Studios 2012-04-05 16:52
Ads