Swift 3 - 动态 vs @objc [英] Swift 3 - dynamic vs @objc
问题描述
将方法标记为@objc 与动态之间有什么区别,你会在什么时候做一个和另一个?
What's the difference between marking a method as @objc vs dynamic, when would you do one vs the other?
以下是 Apple 对动态的定义.
Below is Apple's definition for dynamic.
dynamic 将此修饰符应用于类的任何成员,该成员可以以Objective-C为代表.当你标记一个成员声明时动态修饰符,对该成员的访问始终是动态的使用 Objective-C 运行时调度.对该成员的访问是从未被编译器内联或去虚拟化.
dynamic Apply this modifier to any member of a class that can be represented by Objective-C. When you mark a member declaration with the dynamic modifier, access to that member is always dynamically dispatched using the Objective-C runtime. Access to that member is never inlined or devirtualized by the compiler.
因为用 dynamic 修饰符标记的声明被分派使用 Objective-C 运行时,它们被隐式标记为 objc属性.
Because declarations marked with the dynamic modifier are dispatched using the Objective-C runtime, they’re implicitly marked with the objc attribute.
推荐答案
声明为 @objc
的函数/变量可从 Objective-C 访问,但 Swift 将继续通过静态或虚拟调度.这意味着如果函数/变量通过 Objective-C 框架进行了调整,就像使用 Key-Value Observing 或各种 Objective-C API 修改类时发生的情况一样,从 Swift 和 Objective-C 调用方法会产生不同的结果.
A function/variable declared as @objc
is accessible from Objective-C, but Swift will continue to access it directly via static or virtual dispatch.
This means if the function/variable is swizzled via the Objective-C framework, like what happens when using Key-Value Observing or the various Objective-C APIs to modify classes, calling the method from Swift and Objective-C will produce different results.
使用 dynamic
告诉 Swift 总是引用 Objective-C 动态调度.这是关键值观察等正常工作所必需的.调用 Swift 函数时,会参考 Objective-C 运行时动态调度调用.
Using dynamic
tells Swift to always refer to Objective-C dynamic dispatch.
This is required for things like Key-Value Observing to work correctly. When the Swift function is called, it refers to the Objective-C runtime to dynamically dispatch the call.
这篇关于Swift 3 - 动态 vs @objc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!