gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:24:17 29 4
gpt4 key购买 nike

根据 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/

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