Swift本机基类或NSObject [英] Swift native base class or NSObject
问题描述
我用Swift测试了 isa swizzling ,发现它仅在NSObject是超类时才有效(直接或进一步),或使用'@objc'装饰.否则,它将遵循静态和vtable-dispatch样式,例如C ++.
I tested out some isa swizzling with Swift, and found that it only works when NSObject is a super-class (directly or further up), or by using the '@objc' decoration. Otherwise it will follow a static- and vtable-dispatch style, like C++.
在没有Cocoa/NSObject基类的情况下定义Swift类是否正常?如果我担心的话,这意味着要放弃Objective-C的大部分活力,例如方法拦截和运行时自省.
Is it normal to define a Swift class without a Cocoa/NSObject base class? If it is I'm concerned this means foregoing much of the dynamism of Objective-C, such as method interception and run-time introspection.
动态运行时行为是属性观察器,核心数据,面向方面的功能的核心编程,高阶消息,分析性&日志记录框架等.
Dynamic run-time behavior sits at the heart of features like property observers, Core Data, Aspect Oriented Programming, Higher Order Messaging, analytical & logging frameworks and so on.
使用Objective-C的方法调用样式会将大约20个机器代码操作数添加到方法调用中,因此在某些情况下(许多对具有小主体的方法的紧密调用),C ++样式的静态和vtable分派可以表现更好.
Using Objective-C's style of method invocation adds around 20 machine code operands to a method call, so in certain situations (many tight calls to methods with small bodies) C++ style static and vtable dispatch can perform better.
但是考虑到一般的95-5规则( 95%的性能提升来自于调整5%的代码),从强大的动态功能入手并在何处强化是没有道理的必要的?
But given the general 95-5 rule (95% of performance gains come from tuning 5% of the code), doesn't it makes sense to start with the powerful dynamic features and harden where necessary?
推荐答案
作为NSObject子类的Swift类:
Swift classes that are subclasses of NSObject:
- 本身就是Objective-C类
- 使用
objc_msgSend()
调用(大多数)方法 - 为大多数方法实现提供Objective-C运行时元数据
- are Objective-C classes themselves
- use
objc_msgSend()
for calls to (most of) their methods - provide Objective-C runtime metadata for (most of) their method implementations
不是NSObject子类的Swift类:
Swift classes that are not subclasses of NSObject:
- 是Objective-C类,但仅实现了少数几种方法以实现NSObject兼容性
- 请勿使用
objc_msgSend()
对其方法进行调用(默认情况下) - 不为其方法实现提供Objective-C运行时元数据(默认情况下)
- are Objective-C classes, but implement only a handful of methods for NSObject compatibility
- do not use
objc_msgSend()
for calls to their methods (by default) - do not provide Objective-C runtime metadata for their method implementations (by default)
在Swift中对NSObject进行子类化可以为您提供Objective-C运行时的灵活性,以及Objective-C的性能.如果不需要Objective-C的灵活性,避免使用NSObject可以提高性能.
Subclassing NSObject in Swift gets you Objective-C runtime flexibility but also Objective-C performance. Avoiding NSObject can improve performance if you don't need Objective-C's flexibility.
对于Xcode 6 beta 6,将显示动态属性.这使我们可以指示Swift某个方法应使用动态分配,因此将支持拦截.
With Xcode 6 beta 6, the dynamic attribute appears. This allows us to instruct Swift that a method should use dynamic dispatch, and will therefore support interception.
public dynamic func foobar() -> AnyObject {
}
这篇关于Swift本机基类或NSObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!