ios - Swift 函数中的动态修饰符

标签 ios swift inheritance dynamic dynamic-dispatch

根据 Apple 的说法:

When you mark a member declaration with the dynamic modifier, access to that member is always dynamically dispatched. Because declarations marked with the dynamic modifier are dispatched using the Objective-C runtime, they’re implicitly marked with the @objc attribute.

根据维基百科:

dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time.

Dynamic dispatch is often used in object-oriented languages when different classes contain different implementations of the same method due to common inheritance. For example, suppose you have classes A, B, and C, where B and C both inherit the method foo() from A. Now suppose x is a variable of class A. At run time, x may actually have a value of type B or C and in general you can't know what it is at compile time.

现在,我正在研究 dependency injection框架:Typhoon当我打开 Swift 的示例项目时在所有继承自 Objective-C 类 TyphoonAssembly 的类中,所有注入(inject)依赖项的相关方法都以以下方式包含 dynamic 修饰符:

public dynamic func weatherReportDao() -> AnyObject {
    return TyphoonDefinition.withClass(WeatherReportDaoFileSystemImpl.self)
}

我以为我遗漏了什么,但我不明白运行时要调用的多态操作(方法或函数)在哪里。

这里动态调度的目的是什么?

最佳答案

您的问题的答案在这篇文章中得到了解决:

https://github.com/appsquickly/typhoon/wiki/TyphoonAssembly

基本上在运行时,Typhoon Framework 将用它自己的例程替换您的方法,该例程实现框架的功能并调用您的方法来完成您为其定义的任何工作。

为了让框架能够替换方法,必须动态调度方法。

关于ios - Swift 函数中的动态修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29686506/

相关文章:

ios - 使用 Realm,我应该使用 List 对象还是 Results 对象作为 UITableView 的数据源?

ios - Swift 3 多线程使用哪个队列?

ios - 如何检查在 scenekit iOS 中点击了哪个 SCNNode

iOS:与父 View Controller 通信

java - ServerSocket - 如何保留客户端套接字 ID

ios - Swift - 无法通过导航 Controller 中的自定义选项卡寻呼机传递数据

ios - 如何将代码添加到我的 viewcontroller.swift 以通过导航 Controller 连接的 View ?

ios - Swift:使用开关关闭按钮声音

Java:从父类访问子类方法

c# - 强制在基类内部调用基类虚方法