I'm still kind of new to Objective-C and I'm wondering what is the difference between the following two statements?
[object performSelector:@selector(doSomething)];
[object doSomething];
I'm still kind of new to Objective-C and I'm wondering what is the difference between the following two statements?
[object performSelector:@selector(doSomething)];
[object doSomething];
Basically performSelector allows you to dynamically determine which selector to call a selector on the given object. In other words the selector need not be determined before runtime.
Thus even though these are equivalent:
[anObject aMethod];
[anObject performSelector:@selector(aMethod)];
The second form allows you to do this:
SEL aSelector = findTheAppropriateSelectorForTheCurrentSituation();
[anObject performSelector: aSelector];
before you send the message.
@ennuikiller is spot on. Basically, dynamically-generated selectors are useful for when you don't (and usually can't possibly) know the name of the method you'll be calling when you compile the code.
One key difference is that -performSelector:
and friends (including the multi-threaded and delayed variants) are somewhat limited in that they are designed for use with methods with 0-2 parameters. For example, calling -outlineView:toolTipForCell:rect:tableColumn:item:mouseLocation:
with 6 parameters and returning the NSString
is pretty unwieldy, and not supported by the provided methods.
Selectors are a bit like function pointers in other languages. You use them when you don't know at compile time which method you want to call at runtime. Also, like function pointers, they only encapsulate the verb part of invocation. If the method has parameters, you will need to pass them as well.
An NSInvocation
serves a similar purpose, except that it binds together more information. Not only does it include the verb part, it also includes the target object and the parameters. This is useful when you want to call a method on a particular object with particular parameters, not now but in the future. You can build an appropriate NSInvocation
and fire it later.