Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addTarget:self versus addTarget:nil

I am new in iOS development. I am little confuse when I am adding a button programmatically.When we assign a target to button like:

[button addTarget:self action:@selector(CallMe) forControlEvents:UIControlEventTouchUpInside];

and

[button addTarget:nil action:@selector(CallMe) forControlEvents:UIControlEventTouchUpInside];

It is calling CallMe method in both the cases. Can anybody explain me what is the actual difference between these two lines of code.It will more helpful if anyone can explain the working of addTarget specially.Thank you very much. Help would be appropriated.

like image 779
Rana Kaman Avatar asked Jun 06 '13 06:06

Rana Kaman


3 Answers

If you add self or any other object as the target for an action message the message will be sent to exactly this object.

Adding nil as a target means that the actual target will be searched at runtime when the message is triggered. The lookup starts at the first responder object and continuous from there along the responder chain, that is by trying the object returned by the nextResponder method until an object is found that implements this method. Take a look at the event handling guide for more information on the exact lookup order.

like image 156
Sven Avatar answered Oct 09 '22 09:10

Sven


According to Apple's documentation,

The target object is the parameter send to addTarget method—that is, the object to which the action message is sent. If this is nil, the responder chain is searched for an object willing to respond to the action message.

If you want to remove the action, you can pass nil to remove all targets paired with action and the specified control events on the remove target method,

[button removeTarget:nil action:@selector(CallMe) forControlEvents:UIControlEventTouchUpInside];
like image 1
Nazik Avatar answered Oct 09 '22 09:10

Nazik


Here is description of parameter Target from apple's documentation for UIControl class:

target The target object—that is, the object to which the action message is sent. If this is nil, the responder chain is searched for an object willing to respond to the action message.

like image 1
user1113101 Avatar answered Oct 09 '22 09:10

user1113101