Search code examples
objective-cmacoscocoaibactionnsbutton

Why does an IBAction's sender type have to be id?


I'm learning Cocoa with "Cocoa Programming For Mac OS X right now (the Objective-C edition)" and whenever I create a button with Interface Builder, I have to connect it with one of the classes I am currently working with.

When I control click-drag from the button to my AppDelegate.h file, Xcode will automatically hook the button to my AppDelegate class. If I choose "Action" it will create a method like this:

- (IBAction)onButtonPress:(id)sender {
}

Objective-C's methods work like this:

- (returnType)methodName:(typeOfFirstArgument)firstArgumentName (typeOfSecondeArgument)secondArgumentName

Why do I have to use the type id for the sender instead of NSButton? I know that I hooked the method up with a button. As a consequence, I expect the sender to be a object of type NSButton.

I tried that but it did not work.


Solution

  • The type does not have to be id. You can most definitely change the type and name of the parameter, either using the pop-up when you create the connection, or in the code.

    id is a type meaning "pointer to any ObjC object". A pointer to a specific class works just as well:

    - (IBAction)onButtonPress:(NSButton *)importantButton;