gpt4 book ai didi

objective-c - 了解 Objective-C 中选择器的唯一性

转载 作者:行者123 更新时间:2023-12-01 14:51:19 24 4
gpt4 key购买 nike

如 Apple 指南中所述,我无法理解“选择器”的部分功能。我把我感到困惑的部分加粗了:

In Objective-C, selector has two meanings. It can be used to refer simply to the name of a method when it’s used in a source-code message to an object. It also, though, refers to the unique identifier that replaces the name when the source code is compiled. Compiled selectors are of type SEL. All methods with the same name have the same selector. You can use a selector to invoke a method on an object—this provides the basis for the implementation of the target-action design pattern in Cocoa.

Methods and Selectors For efficiency, full ASCII names are not used as method selectors in compiled code. Instead, the compiler writes each method name into a table, then pairs the name with a unique identifier that represents the method at runtime. The runtime system makes sure each identifier is unique: No two selectors are the same, and all methods with the same name have the same selector.

谁能解释一下这些位?另外,如果不同的类有同名的方法,它们是否也有相同的选择器?

最佳答案

所有选择器都是唯一的——无论是在编译时还是动态地在运行时通过 sel_getUid() 或首选的 sel_registerName()(后者在很大程度上是首选,前者由于历史原因仍然存在)——为了速度

背景故事:要调用一个方法,运行时需要一个选择器来标识要调用的内容以及将调用它的对象。这就是为什么 Objective-C 中的每个方法调用都有两个参数:明显且广为人知的 self 和不可见的隐含参数 _cmd_cmd 是当前执行的方法的 SEL。也就是说,您可以将此代码粘贴到任何方法中以查看当前正在执行的方法的名称(选择器):

NSLog(@"%@", NSStringFromSelector(_cmd));

请注意 _cmd 不是全局的;这真的是你的方法的一个论点。见下文。

通过唯一化选择器,所有基于选择器的操作都是使用指针相等性测试而不是字符串处理或任何指针取消引用来实现的。

特别是每次调用方法时:

[someObject doSomething: toThis withOptions: flags]; // calls SEL doSomething:withOptions:

编译器生成此代码(或非常密切相关的变体):

objc_msgSend(someObject, @selector(doSomething:withOptions:), toThis, flags);

objc_msgSend() 做的第一件事是检查 someObject 是否为 nil,如果是则短路 (nil-eats-message)。接下来(忽略标记指针)是在 someObject 的类中查找选择器(实际上是 isa 指针),找到实现 ,并调用它(使用尾调用优化)。

找到实现 的事情必须要快,要让它变得非常快,您希望找到方法实现的关键是尽可能快速和稳定。要做到这一点,您希望 key 可以直接使用并且在全局范围内对于流程是唯一的。

因此,选择器是唯一的。

它也恰好可以节省内存,这是一个了不起的好处,但是如果可以将消息发送速度提高 2 倍(但不是 10 倍是 2 倍——甚至是 2 倍内存是 2 倍速度——),信使将使用比现在更多的内存——虽然速度很关键,但内存使用当然也很关键。

如果你真的想深入了解 objc_msgSend() 的工作原理,我写了一个 bit of a guide .请注意,它有点过时,因为它是在标记指针、 block 实现和 ARC 被公开之前编写的。我应该更新文章。

关于objective-c - 了解 Objective-C 中选择器的唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11051528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com