I am still learning Objective-C but I like to know the “why” behind everything I learn.
I would like to know why an Objective-C method requires that the types are enclosed in parentheses, such as:
- (IBAction) myAction: (UIButton *) sender;
Instead of:
- IBAction myAction: UIButton *sender;
I’ve tried finding answers and thought about it quite a bit but can’t seem to see what the reasoning is for.
What troubles me is sometimes I actually forget that the asterisk (*) needs to be inside the parentheses, sometimes I accidentally type the following incorrect signature:
- (IBAction) myAction: (UIButton) *sender;
As to me, this more logically represents the argument is a pointer, not the type.
That’s C casting syntax:
Think of it as casting the parameters and return value to specific types.
In the very early days of Objective-C return values and parameters defaulted to the
idtype. So you’d see method declarations like this:For numerous reasons it became preferable to strongly type the return value and parameters in Objective-C code, to the point that all return values and parameters are strongly typed, even if they’re
id:The asterisk is also C syntax.
UIButton*is a specific type, different fromUIButtonandUIButton**. You could do this:and then use
UIButtonRefinstead ofUIButton*: