selector in Objective-C

selector在Objective-C裡面,通常被拿來當作callback function使用。以下是網路上看來的,先記起來,以免日後要找時忘記。

SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It’s not a function pointer and you can’t pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:

-(void)methodWithNoArguments;
SEL noArgumentSelector = @selector(methodWithNoArguments);

-(void)methodWithOneArgument:(id)argument;
SEL oneArgumentSelector = @selector(methodWithOneArgument:); // notice the colon here

-(void)methodWIthTwoArguments:(id)argumentOne and:(id)argumentTwo;
SEL twoArgumentSelector = @selector(methodWithTwoArguments:and:); // notice the argument names are omitted

Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:

-(void)someMethod:(NSTimer*)timer;

So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:

@implementation MyObject

-(void)myTimerCallback:(NSTimer*)timer
{
    // do some computations
    if( timerShouldEnd ) {
      [timer invalidate];
    }
}

@end

// ...

int main(int argc, const char **argv)
{
    // do setup stuff
    MyObject* obj = [[MyObject alloc] init];
    SEL mySelector = @selector(myTimerCallback:);
    [NSTimer scheduleTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
    // do some tear-down
    return 0;
}

In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds.

假如一個function在該做的事完成後要執行selector callback,可以類似下面這樣寫

-(void) someMethod:(id)handler selector:(SEL)selector {
    // some codes here...

    // execute callback function
    if( handler != nil && selector != nil && [handler respondsToSelector:selector] ) {
        [handler performSelector:selector];
    }
}

Reference:
http://stackoverflow.com/questions/297680/how-do-sel-and-selector-work-in-iphone-sdk

Tags: , , ,

Leave a Reply