2

In Objective-C, what does "(UIButton *)sender" mean and why is it not "UIButton *sender"? Or some NSObject in place of UIButton. This is more a question about the precedence of the asterisk...

- (IBAction)digitPressed:(UIButton *)sender {
   //...
}
kdask
  • 23
  • 2
  • You might find these answers interesting: http://stackoverflow.com/questions/2189212/why-object-dosomething-and-not-object-dosomething/2214980#2214980 and http://stackoverflow.com/questions/1304176/objective-c-difference-between-id-and-void/1304277#1304277 – bbum Feb 09 '12 at 04:18

1 Answers1

6

It's not about precedence in this case. The parentheses aren't a cast.

This is the syntax in ObjC for a method declaration, and it says that the parameter called sender is of type UIButton *.

The asterisk goes with the UIButton because they together name the type of the argument. In this case, since it's an action method coming from a button, you're using a UIButton*. In the general case, of course, a method may have parameters of any type, as long as the caller is calling it correctly. :)

Ben Zotto
  • 70,108
  • 23
  • 141
  • 204
  • Ah, I get it. This will take just a little getting used to. What you said makes sense now so I can stop racking my brain. Spent a bit too much time Googling in the wrong direction. Thanks! – kdask Feb 09 '12 at 00:27
  • 1
    Sorry, I don't understand "`The parentheses aren't a cast.`" line. You're casting the `sender` parameter, which defaults to `id`, to a more specific type, `UIButton *`. How is that not a cast? – NSGod Feb 09 '12 at 03:09
  • @NSGod: That strains the definition of what a "cast" is. It may share a similar syntax, but arguments can be not only object references, but structs and other primitives of arbitrary size. The compiler needs to know about those things in advance for it to work. Just because an argument *defaults* to `id` when unspecified doesn't mean that's the actual inherent type of all arguments to a method. – Ben Zotto Feb 09 '12 at 17:45
  • @quixoto: sorry, but it's a cast. See my answer for an explanation. Whether you cast the local parameter several times within the method body or once in the method name, it's still a cast. It's simply more practical to do it in the method name. – NSGod Feb 10 '12 at 04:43
  • @NSGod: This is simply not the case. It's an interesting conceptual model for the syntax, but is not what's actually happening. I've commented on your answer with more detail. – Ben Zotto Feb 10 '12 at 21:33