本文主要是介绍IT English Collection(17) of Selector,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1 前言
本文是一篇关于选择器(Selector)的文章,Selector可以理解为一个方法名,具体见下文。
转载请注明出处:http://blog.csdn.net/developer_zhang
2 详述
2.1 原文
A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled. A selector by itself doesn’t do anything. It simply identifies a method. The only thing that makes the selector method name different from a plain string is that the compiler makes sure that selectors are unique. What makes a selector useful is that (in conjunction with the runtime) it acts like a dynamic function pointer that, for a given name, automatically points to the implementation of a method appropriate for whichever class it’s used with. Suppose you had a selector for the method run
, and classes Dog
, Athlete
, and ComputerSimulation
(each of which implemented a method run
). The selector could be used with an instance of each of the classes to invoke its run
method—even though the implementation might be different for each.
Getting a Selector
Compiled selectors are of type SEL
. There are two common ways to get a selector:
-
At compile time, you use the compiler directive
@selector
.SEL aSelector = @selector(methodName);
-
At runtime, you use the
NSSelectorFromString
function, where the string is the name of the method: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.
Using a Selector
You can invoke a method using a selector with performSelector:
and other similar methods.
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.)
2.2 生词
plain [pleɪn] adj. 平的;简单的
conjunction [kən'dʒʌŋ(k)ʃ(ə)n] n. 结合;[语] 连接词
dynamic [daɪ'næmɪk] adj. 动态的;动力的
appropriate [ə'prəʊprɪət] adj. 适当的 vt. 占用;拨出
Athlete ['æθliːt] n. 运动员,体育家
directive [dɪ'rektɪv; daɪ-] n. 指示;指令
technique [tek'niːk] n. 技巧,技术
situations [ˌsitjuˈeiʃənz] n. 状况;情境
3 结语
以上是所有内容,希望对大家有所帮助。
这篇关于IT English Collection(17) of Selector的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!