What is the Objective-C equivalent to a .Net delegate?

242 views Asked by At

In .Net when I have an object that has an event I can register to handle that event via a delegate:

void Test()
{
    Button button = new Button();
    button.Click  += new EventHandler(OnClick);
}
void OnClick(object sender, EventArgs e)
{
    text1.Text = "The Button Was Clicked";
}

How do I do this sort of thing in Objective-C? Specifically I'm trying to handle the ccTouchEnded of a SneakyButton. I thought it would be something like this:

SneakyButton* mybutton = [SneakyButton button];
[mybutton ccTouchEnded:self.onButtonDown];

- (void)onButtonDown:(UITouch *)touch withEvent:(UIEvent *)event
{
    CCLOG(@"The Button Was Clicked");
}
3

There are 3 answers

0
justin On BEST ANSWER

Cocoa and CocoaTouch often uses "Target/Action".

  • Target: an objc object. the target is what gets messaged.
  • Action: a selector. the action is the selector to message the target with.

In that sense, the action is the equivalent.

When the target/action is performed, it would take this general form:

[target performSelector:action withObject:someParameter];

of course, the parameter list will vary in the real world.

The UIControl class is quite small - read it for more info on the subject. It will give you a good idea of a control's target/action support and the interfaces you'll use for handling these events. NSControl is the Cocoa counterpart, but that's a much larger class - it defines much more than Target/Action interfaces.

0
rob mayoff On
[mybutton addTarget:self action:@selector(onButtonDown:withEvent:)
    forControlEvents:UIControlEventTouchUpInside];

Note that the first argument to onButtonDown:withEvent: will be the button object, not the touch object.

You can read more about the target/action pattern in the Cocoa Fundamentals Guide.

0
paulsm4 On

Actually, it might be something like this:

[mybutton ccTouchEnded:self.onButtonDown];

and

(void)myButtonClick:(id)sender {
    mylabel.text = @"The Button Was Clicked";
}

This link might help: http://bynomial.com/blog/?p=13