objective c 运行时功能是什么?

What are objective c runtime features?

在博客中 post 我刚刚阅读:

'Swift allows us to extend classes from NSObject to get Objective-C runtime features for an object. It also allows us to annotate Swift methods with @objc to allow the methods to be used by the Objective-C runtime.'

我不明白 objective-C 运行时功能这个术语。这是否意味着该代码也可以在 objective-C 项目中使用?

引用 apple docs

The Objective-C runtime is a runtime library that provides support for the dynamic properties of the Objective-C language, and as such is linked to by all Objective-C apps. Objective-C runtime library support functions are implemented in the shared library found at /usr/lib/libobjc.A.dylib.

API 主要用于开发 Objective-C 和其他语言之间的桥接层,或用于低级调试。您很可能不需要使用它。

即使在没有一行 Objective-C 代码的情况下编写,每个 Swift 应用程序都会在 Objective-C 运行时内执行,因此您可以访问它。

你可以做 swizzling

Objective-C 运行时间

Swift 可以使用 Objective-C Runtime 库。

C + extra layer + Objective-C Runtime = Objective-C

它使用类似 API,但针对 iOS 或 MacOS 等不同平台的不同实现。

[Message dispatch]

它包含:

  • 基本结构如class、对象、变量、属性、方法
  • 用于处理这些结构的函数
    • 内省 - get/read 运行时有关 class/object 的信息。例如实例变量、方法名称、方法参数。 class_getName
    • 反射——修改自身的结构和行为。比如分配新的class,添加变量,添加方法。 class_addMethod
    • objc_msgSend - 基于消息调度
    • Swizzling - swap 方法在运行时的实现。 method_exchangeImplementations。 [Objective C], 混合示例

使用 为 Objective-C 公开 Swift 的 API 并为 Swift 代码添加动态行为。当您需要一些通常的 swift 方法无法做到的事情时,它很有用。很好的例子是 KVO, swizzling...

[KVO]

Objective-C 对比 Swift

Swift 具有更好的性能(基于 table 调度)但 Objective-C 是更动态的语言 [more]