Swift 3 - dynamic vs @objc

前端 未结 3 724
轮回少年
轮回少年 2020-12-13 17:25

What\'s the difference between marking a method as @objc vs dynamic, when would you do one vs the other?

Below is Apple\'s definition for dynamic.

相关标签:
3条回答
  • 2020-12-13 17:56

    As that quote says, dynamic implies @objc.

    Unless you specify a class as being dynamic, the compiler is free to optimize away and inline its methods. This brings huge performance benefits, but it means that you can't change those method implementations at run time. If you're planning to mess around with those methods at runtime using the reflection capabilities of the Objective C runtime, you'll need to use dynamic. You'll incur a performance penalty (your code will run at Objective C levels of speed, rather than near C-like levels), but you'll gain that extra dynamism.

    0 讨论(0)
  • 2020-12-13 17:59

    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.

    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.

    0 讨论(0)
  • 2020-12-13 18:03

    To work with Objective-C from Swift you have at least two reserved words:

    • @objc[About] - Compile time - To expose Swift's api for Objective-C runtime. For example a framework which was written on Swift can use @objc for:

      1. using #selector[About] in a Swift code
      2. opening public functionality for Objective-C consumers
    • dynamic - Run time - to enable a message dispatch(Objective-C's world) for NSObject object, which is different than virtual dispatch (table dispatch) (Swift's world). It is used for:

      1. KVO
      2. class extensions to have a possibility to override an extension function
      3. swizzling[Example]

    Before Swift v4 dynamic included @objc

    0 讨论(0)
提交回复
热议问题