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.
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.
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With