views:

69

answers:

3

Let's say I have a method called foo. What's the difference between:

[self foo];

and

[self performSelector:@selector(foo)];

Are they the same? The first one seems so much easier, so why would you ever want to use the second one?

+1  A: 

Well, say you were getting a SEL from somewhere else, and you just wanted to execute it, you'd use this method.

Otherwise, yeah, you'd usually want to use the first example.

Jacob Relkin
Can the first example be used if the selector takes arguments?
awakeFromNib
@awakeFromNib Of course.
Jacob Relkin
+5  A: 

From the docs:

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 MYYN
theMikeSwan
+1  A: 

The first sends a message to an object and so does the second. In almost all cases, you should use the first. It's quicker and clearer. However, the second has its uses. For instance, you can use it in a situation where you would need to supply a call back.

Another powerful use is in combination with NSSelectorFromString(). You can literally decide what message to use at run time based on a string in a configuration file or from user input (don't forget to validate it!). You can even build selector names using NSString -stringWithFormat: etc. For instance, this parser kit uses the technique to inform the program when parser rules have been matched.

JeremyP