【Objective-C】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:

1. -(void)methodWithNoArguments;
2. SEL noArgumentSelector = @selector(methodWithNoArguments);
3.  
4. -(void)methodWithOneArgument:(id)argument;
5. SEL oneArgumentSelector = @selector(methodWithOneArgument:); // notice the colon here
6.  
7. -(void)methodWIthTwoArguments:(id)argumentOne and:(id)argumentTwo;
8. 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:

1. -(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:

01. @implementation MyObject
02.  
03. -(void)myTimerCallback:(NSTimer*)timer
04. {
05. // do some computations
06. if( timerShouldEnd ) {
07. [timer invalidate];
08. }
09. }
10.  
11. @end
12.  
13. // ...
14.  
15. int main(int argc, const char **argv)
16. {
17. // do setup stuff
18. MyObject* obj = [[MyObject alloc] init];
19. SEL mySelector = @selector(myTimerCallback:);
20. [NSTimer scheduleTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
21. // do some tear-down
22. return 0;
23. }

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

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

1. -(void) someMethod:(id)handler selector:(SEL)selector {
2. // some codes here...
3.  
4. // execute callback function
5. if( handler != nil && selector != nil && [handler respondsToSelector:selector] ) {
6. [handler performSelector:selector];
7. }
8. }

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

猜你喜欢

转载自moto0421.iteye.com/blog/1623921