objective-c - 是否 NSSelectorFromString( @"methodName");创建一个对象?

标签 objective-c cocoa

到目前为止,我已经学会了在 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/

相关文章:

swift - NSCollectionView 自定义布局启用滚动

iphone - 在 Objective-C 中实例化对象时出现语法错误

objective-c - UILabel 文本末尾包含多个空格

cocoa - 如何在 Cocoa 中使用 Bindings+CoreData 实现 iTunes 风格的源列表?

c++ - 通过元编程将 c++ 简化为objective-c/cocoa 桥接?

编译从书中逐字复制的代码会导致编译器错误

cocoa - 如何在 Cocoa 中处理同时和重叠的按键

ios - 无法渲染尺寸大于 640x640 的视频

objective-c - 错误 ITMS-90283 : "Invalid Provisioning Profile"

ios - 如何在 Objective-C 中将 NSString 转换为 NSMutableString?