Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between AnyObject and UIbutton as sender?

When defining an IBAction, there's an option for Anyobject and UIButton, both works, what's the difference?

like image 356
Bright Future Avatar asked May 27 '15 06:05

Bright Future


People also ask

How to use sender in UIButton?

If you want to use a property of the sender that is specific to the class UIButton, like sender.currentTitle, the compiler will object if it does not know that the sender is a UIButton. So you have to 'cast' the sender into UIButton either before the property is referenced or as your question suggests, in the method call itself.

How do I call a class from a UIButton in objectivec?

In ObjectiveC the class is typically listed as (id). I assume that is what Swift means by "Any". If you know that the action will only be called by a UIButton then you can make that (UIButton *) in ObjectiveC and I assume that is the same as Swift's UIButton.

What is [anyobject] in Objective-C?

It’s equivalent to ‘id’ in Objective-C. AnyObject can represent an instance of any class type. If you specifically define the array as [ AnyObject ], you are indicating to the compiler that you are aware that the elements are of the reference data type only.

How to know who sent the message inside the ibaction?

If you need to know who sent the message inside the IBAction, use sender: UIButton Otherwise, you can use Any, that will make no difference. I usually prefer to know who the sender is.


1 Answers

Yes, both works. The difference is just that by declaring it to a button, you get a typecasted reference as UIButton instead of AnyObject (or id in Objective-C). If you did not do that you will have to do it manually inside the code.

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.

For example a refresh button, you might have to do a refresh programatically. If you have set your action parameter to UIButton, you have to send an UIButton (but why??? You are doing it programatically, right?). Whereas if it is AnyObject, you can send 'self'. Which will also make you distinguish whether the refresh was done on action or programatically.

Hope that explains. Sorry for no code. I am not into Swift coding much. Edits are welcome.

EDIT

So, even if it is AnyObject, it does have your UIButton properties. Just type cast it to use them.

like image 94
Mayur Deshmukh Avatar answered Sep 19 '22 15:09

Mayur Deshmukh