Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is use of performSelector in iOS

What is the role of performSelector?

Comparing:

[self btnClicked];

and

[self performSelector:@selector(btnClicked)];

-(void)btnClicked
{
    NSLog(@"Method Called");
}

both are woking fine for me. What is difference between these two. [self btnClicked] and [self performSelector:@selector(btnClicked)];

like image 726
QueueOverFlow Avatar asked Jul 18 '12 10:07

QueueOverFlow


2 Answers

The two are pretty identical when used as you have demonstrated, but the latter has the advantage that you can dynamically determine which selector to call at runtime.

SEL selector = [self gimmeASelectorToCall];
[self performSelector: selector];

[Source]

like image 72
James Webster Avatar answered Oct 15 '22 16:10

James Webster


Apple doc is your friend.

NSObject Protocol Reference

It

Sends a specified message to the receiver and returns the result of the message.

In particular:

The performSelector: method is equivalent to sending an aSelector message directly to the receiver. For example, all three of the following messages do the same thing:

id myClone = [anObject copy];
id myClone = [anObject performSelector:@selector(copy)];
id myClone = [anObject performSelector:sel_getUid("copy")];

However, the performSelector: method allows you to send messages that aren’t determined until runtime. A variable selector can be passed as the argument:

SEL myMethod = findTheAppropriateSelectorForTheCurrentSituation();
[anObject performSelector:myMethod];

The aSelector argument should identify a method that takes no arguments. For methods that return anything other than an object, use NSInvocation.

Hope that helps.

like image 43
Lorenzo B Avatar answered Oct 15 '22 18:10

Lorenzo B