UIButton vs AnyObject in IBAction


When creating an action for a button you have the option of selecting the type AnyObject or UIButton.

One explanation I found is “You should prefer leaving it to AnyObject in case the action has some code you would like to call from anywhere else, rather than just the button action”. I have done this in apps.

So why / when would you use UIButton as the type?


I would use UIButton so that you get the real type. But you only need to do this if you want to do something dynamic with the button. Most of the time in practice this only occurs when you hook multiple buttons to the same @IBAction (good in some situations, but not all). This helps you not have to create 15 different @IBAction methods for something like your own number pad.

In most situations you will have a unique button tied to a unique @IBAction method, so you won’t need to know which button was pressed using the sender parameter. You’ll again only see this parameter as useful when you need to distinguish which, when multiple are tied to the same logic.

The default of AnyObject works, but requires you cast it to UIButton before you can use it in code (boilerplate code you can avoid).


Ah!! I forgot about that. When I first started learning Obj C I remember a Stanford (I think) tutorial that used UIButton for a calculator. Thanks.