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!
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With