开发者

Calling Objective-C methods

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

[self foo];

a开发者_如何学Pythonnd

[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?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜