objective-c - 为什么 Objective-C 不支持私有(private)方法?

标签 objective-c objective-c-runtime

我在 Objective-C 中看到了许多声明半私有(private)方法的策略,但似乎没有办法制作真正私有(private)的方法。我接受。但是,为什么会这样?我基本上说的每一个解释都是:“你做不到,但这是一个非常接近的近似值。”

有许多关键字应用于控制其范围的 ivars(成员),例如@private@public@protected。为什么方法也不能这样做?看起来运行时应该能够支持的东西。有没有我缺少的基本哲学?这是故意的吗?

最佳答案

答案是……嗯……很简单。事实上,简单性和一致性。

Objective-C 在方法分派(dispatch)时是纯动态的。特别是,每个方法分派(dispatch)都经过与所有其他方法分派(dispatch)完全相同的动态方法解析点。在运行时,每个方法实现都具有完全相同的公开,并且由 Objective-C 运行时提供的所有与方法和选择器一起使用的 API 在所有方法中的工作方式都是相同的。

正如许多人已经回答的那样(这里和其他问题),支持编译时私有(private)方法;如果一个类没有在其公开可用的接口(interface)中声明一个方法,那么就您的代码而言,该方法也可能不存在。换句话说,您可以通过适本地组织项目来实现编译时所需的所有各种可见性组合。

将相同的功能复制到运行时几乎没有什么好处。这会增加大量的复杂性和开销。即使如此复杂,它仍然不会阻止除了最随意的开发人员之外的所有开发人员执行您所谓的“私有(private)”方法。

EDIT: One of the assumptions I've noticed is that private messages would have to go through the runtime resulting in a potentially large overhead. Is this absolutely true?

Yes, it is. There's no reason to suppose that the implementor of a class would not want to use all of the Objective-C feature set in the implementation, and that means that dynamic dispatch must happen. However, there is no particular reason why private methods couldn't be dispatched by a special variant of objc_msgSend(), since the compiler would know that they were private; i.e. this could be achieved by adding a private-only method table to the Class structure.

私有(private)没有办法 短路此检查的方法或 跳过运行时?

It couldn't skip the runtime, but the runtime wouldn't necessarily have to do any checking for private methods.

That said, there's no reason that a third-party couldn't deliberately call objc_msgSendPrivate() on an object, outside of the implementation of that object, and some things (KVO, for example) would have to do that. In effect, it would just be a convention and little better in practice than prefixing private methods’ selectors or not mentioning them in the interface header.

但是,这样做会破坏语言的纯动态特性。不再每个方法分派(dispatch)都通过相同的分派(dispatch)机制。相反,您将处于大多数方法以一种方式运行而一小部分只是不同的情况。

这超出了运行时的范围,因为 Cocoa 中有许多机制建立在 Objective-C 的一致动态之上。例如,Key Value Coding 和 Key Value Observation 要么必须进行大量修改以支持私有(private)方法(很可能是通过创建可利用的漏洞),要么私有(private)方法将不兼容。

关于objective-c - 为什么 Objective-C 不支持私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2158660/

相关文章:

ios - 更新到 Xcode 5.1 后出现超过 130 个错误

c++ - 完全限制对文件夹的所有类型的访问

ios - 所有子类的 class_copyPropertyList 也

objective-c - 参数数量未知的 resolveInstanceMethod

当方向只允许横向时,iOS 9 UIImagePickerControllerSourceTypePhotoLibrary 崩溃

ios - 如何在 Parse 的安装类中应用更新删除查询?

iphone - 将大量数据插入 Core Data 需要多少时间

objective-c - Objective C 运行时 - 内置类与自定义类?

objective-c - NSObject 中的保留计数是如何实现的?

objective-c - 运行时编程动态方法时使用 ARC 编译时出错