翻譯自這里
selector
是一個對象(object)選擇執行某個方法的名稱,或者是代碼編譯后用來唯一標識一個方法。selector
自己不能做任何事,它只是定義了一個方法。selector
與普通字符串的區別就是編譯器確保它是唯一的。它只有在運行時扮演類似動態方法指針的角色,也就是正確指向一個類的實現文件中的方法。
例如,你創建了 run
方法,和 Dog, Athlete, ComputerSimulation
這些類,并且這些類都實現了 run
方法。對象可以通過 selector
調用各自的 run
方法。
獲取 selector
SEL
是selector
編譯后的類型,通常有兩種方式獲取 selector
:
- 在編譯時期,用
@selector
SEL aSelector = @selector(methodName);
- 在運行時期,用
NSSelectorFromString
這個方法
SEL aSelector = NSSelectorFromString(@"methodName");
You use a selector created from a string when you want your code to send a message whose name you may not know until runtime.
使用 selector
你可以通過 performSelector:
或其它類似的方法來調用一個方法
SEL aSelector = @selector(run);
[aDog performSelector:aSelector];
[anAthlete performSelector:aSelector];
[aComputerSimulation performSelector:aSelector];
(You use this technique in special situations, such as when you implement an object that uses the target-action design pattern. Normally, you simply invoke the method directly.)