.netobjective-ckobold2d

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


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");
}

Solution

  • Cocoa and CocoaTouch often uses "Target/Action".

    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.