IOS pressed a button?

I would like to know what the difference is:

- (IBAction)operationPressed:(UIButton *)sender { } 

and:

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

I see that xcode is trying to add extra extra help when completing the auto when using id. so which one is the right one to use and why?

thanks

+4
source share
3 answers

Technically, this does not matter: the declared type of UIButton* does not guarantee that calls with objects of other types are impossible. The fitst style allows you to access the UIButton properties using the "point syntax", and the second style allows you to reuse the handler for other user interface objects without causing your readers to wonder what is happening.

For example, if you know that the event handler is used only with buttons, you can declare the sender type as UIButton , and then do this:

 - (IBAction)operationPressed:(UIButton *)sender { sender.adjustsImageWhenHighlighted = YES; } 

In the second declaration, you need to write the following:

 - (IBAction)operationPressed:(id)sender { [sender setAdjustsImageWhenHighlighted:YES]; } 

On the other hand, if you plan to reuse a handler for different user interface objects, the second approach is preferable.

+3
source

id is a data type that will contain all other data types, which is useful if you want to save what the type does not know at run time.

In cases where you know a type (like this one), it is better to use this type on top of id , because it uses fewer bytes to store it.

+1
source

When you implement this method with a specific class (i.e. UIButton ), Xcode will provide you with additional help. For example, it will autofill more material and give you errors if you send messages to a button that it cannot understand. If the compiler only knew that the sender is of type id , it will not be able to help you.

On the other hand, if you have several buttons, and some of them are a subclass of UIControl , but not UIButton , and all of you want them to run operationPressed , then you might want to set the sender by entering UIControl or id .

So basically, in cases where you know what the sender type will be, life is easier if you tell Xcode what the sender type will be. In cases where you do not know, use id .

+1
source

Source: https://habr.com/ru/post/1481606/


All Articles