0

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
  • If you're interested in the internals, you may want to have a look at the objc_msgSend function, which Objective-C uses internally to resolve message calls Commented Aug 1, 2010 at 9:36

3 Answers 3

5

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];
Sign up to request clarification or add additional context in comments.

1 Comment

@selector() is also used when registering as the observer of an object, using NSTimer, using sheets & alerts, and performing a selector after a delay.
1

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.

1 Comment

Can the first example be used if the selector takes arguments?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.