Ankit Manglik
Ankit Manglik

Reputation: 21

What is the difference between calling the methods in iOS

suppose i call with

[self methodname] 

and other with

[self performSelector:@selector(methodname) withObject:nil];

Upvotes: 2

Views: 193

Answers (2)

Sport
Sport

Reputation: 8975

[self methodname]` is shorter and easier to read, write and comprehend.

[self performSelector:@selector(methodname) withObject:nil]` makes it possible to execute arbitrary selectors. If you save the selector in a variable, then you can execute it later on without knowing the method you invoke.

//Self works like this in oops and self works as setter for your class. It also indicates that u r using getter and setter method.

Upvotes: 1

Gabriele Petronella
Gabriele Petronella

Reputation: 108159

No difference whatsoever.

Straight from the documentation of performSelector:

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")];

While there's no difference in the specific case, however, the reason why performSelector: exists is that it allows invoking an arbitrary selector that may not be available at compile time, as discussed in the doc:

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 considerations above also apply to the two variants performSelector:withObject:, performSelector:withObject:withObject:.

Please also note that this doesn't hold true for another set of methods, namely

  • performSelector:withObject:afterDelay:
  • performSelector:withObject:afterDelay:inModes:
  • performSelectorOnMainThread:withObject:waitUntilDone:
  • performSelectorOnMainThread:withObject:waitUntilDone:modes:
  • performSelector:onThread:withObject:waitUntilDone:
  • performSelector:onThread:withObject:waitUntilDone:modes:
  • performSelectorInBackground:withObject:

Further info here: Does performSelector perform right away or is it scheduled to be performed?

Upvotes: 4

Related Questions