到目前为止,我已经学会了在 Obj-C 中创建对象的这些方法:
[[FooClass alloc] init]
[FooClass new]
[NSNumber numberWithInt:1]
现在我遇到了:
SEL aSelector = NSSelectorFromString(@"methodName");
这个语法让我很困惑。
aSelector 是类 SEL 的一个实例吗,使得 NSSelectorFromString 成为不遵循 Obj-C 语法的工厂方法?
注意:根据 Apple 文档:
“编译的选择器属于类型 SEL。”
“当您希望代码发送一条您可能直到运行时才知道其名称的消息时,您可以使用从字符串创建选择器。”
最佳答案
NSSelectorFromString()
是一个函数,而您的前 3 个示例是方法。这只是函数的语法。它是自行调用的,而不是由任何特定对象调用。
就选择器而言:
根据文档:
SEL
Defines an opaque type that represents a method selector.
typedef struct objc_selector *SEL;
Discussion Method selectors are used to represent the name of a method at runtime. A method selector is a C string that has been registered (or “mapped“) with the Objective-C runtime. Selectors generated by the compiler are automatically mapped by the runtime when the class is loaded.
它是一个结构,而不是一个类。
关于objective-c - 是否 NSSelectorFromString( @"methodName");创建一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24068590/