根据 Apple 的说法:
When you mark a member declaration with the
dynamic
modifier, access to that member is always dynamically dispatched. Because declarations marked with thedynamic
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
, andC
, whereB
andC
both inherit the methodfoo()
fromA
. Now supposex
is a variable of classA
. At run time,x
may actually have a value of typeB
orC
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/