@objc关键字扩展子类行为 [英] @objc keyword extension subclass behaviour

查看:166
本文介绍了@objc关键字扩展子类行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么在这里需要@objc关键字来编译代码吗?

Can someone explain why @objc keyword is needed here to compile the code?

据我了解,此关键字用于工作ObjC消息方法分派.但这不是NSObject实例.

As I understood this keyword is used in order to work ObjC message method dispatch. But this is not an NSObject instance.

 class MyClass {
 }

 extension MyClass {
     @objc func extensionMethod() { /// THIS LINE
         print("A")
     }
 }

 class SubClass: MyClass {
     override func extensionMethod() {
         print("B")
     }
 }

@objc关键字和dynamic一样都启用消息分发吗?还是不?

Does @objc keyword enable message dispatch as well as dynamic? Or not?

推荐答案

@objc关键字和dynamic一样都启用消息分发吗?

Does @objc keyword enable message dispatch as well as dynamic?

通常不行.通常,@objc属性本身只是将给定的类成员暴露给Objective-C – Swift仍然可以使用表或静态分派自由地对其进行分派.如果您想让Swift在调用它时使用消息分发,则需要将该成员标记为dynamic.

Not usually. Usually, the @objc attribute on its own just exposes a given class member to Objective-C – Swift is still free to dispatch to it either using table or static dispatch. You would need to mark the member as dynamic if you wanted Swift to use message dispatch when calling it.

但是,对于非最终@objc扩展成员,Swift会自动将其推断为dynamic.为什么?因为出于互操作性的原因,Swift允许@objc扩展成员覆盖和覆盖(就像您可以在子类类别中覆盖Obj-C方法的方式一样).为了实现此行为,Swift依赖于Obj-C消息调度.

However, for a non-final @objc class extension member, Swift will automatically infer it to be dynamic. Why? Because for interoperability reasons, Swift allows @objc extension members to override and be overridden (much like how you can override an Obj-C method in a subclass category). In order to achieve this behaviour, Swift relies on Obj-C message dispatch.

因此,在扩展名中,@objc推断dynamic.您不能覆盖扩展成员而不将其暴露给Obj-C运行时,因为扩展成员当前无法添加到Swift类vtable(因为Swift vtable当前不能在运行时动态地向其添加成员).

Therefore, in an extension, @objc infers dynamic. You cannot override an extension member without exposing it to the Obj-C runtime because extension members cannot currently be added to Swift class vtables (as Swift vtables currently cannot have members dynamically added to them at runtime).

但这不是NSObject实例.

在Apple平台上(即具有Obj-C互操作的平台),所有所有 Swift类都在Obj-C运行时公开,并且所有类都隐式继承自称为,符合NSObjectProtocol.因此,Swift类无需从NSObject继承就可以利用消息分发的优势.

On Apple platforms (i.e those with Obj-C interop), all Swift classes are exposed to the Obj-C runtime, and all implicitly inherit from a special Obj-C base class called _SwiftObject, which conforms to NSObjectProtocol. So Swift classes are able to take advantage of message dispatch without having to inherit from NSObject.

这篇关于@objc关键字扩展子类行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆