Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C delegates vs Java listeners

I've read a bunch of articles and readings on Objective-C delegates, trying to understand them. Coming from Java, they seem very much like Java listeners. For example, let's say I had a button in Java. When the button is pushed, I want something to happen. My code might look something like this:

ButtonListener myButtonListener = new ButtonListener();    
someButton.addActionListener(myButtonListener);
...

class ButtonListener implements ActionListener
{
   public void actionPerformed(ActionEvent e)
   {

    }
}

Something like that. In objective-c it seems that I would do something along the lines of calling a setDelegate method for my button and passing it the "listener" as a delegate. The actual button class would then probably check if that delegate responded to some selector (ie. actionPerformed). If I'm thinking about this the right way, it does seem like delegates are just like listeners. Is that correct? Are there any major differences?

Thanks!

like image 402
JPC Avatar asked May 23 '11 20:05

JPC


1 Answers

You're pretty much on the button there. The only real difference is delegates in obj-c generally implement multiple functions to perform various actions on events regarding the object they are delegating. For example, the UITextViewDelegate has the methods:

– textViewShouldBeginEditing:
– textViewDidBeginEditing:
– textViewShouldEndEditing:
– textViewDidEndEditing:

The only real difference I've found is you can't create your delegates inline, the way you can in java like:

someButton.setOnClickListener ( new View.OnClickListener {
    @Override
    public void onClick() {
        //do stuff
    }
});
like image 133
Dan F Avatar answered Oct 15 '22 07:10

Dan F