ObjC 对象上的 public swift 函数是动态还是静态调度的?
Are public swift functions on ObjC objects dynamically or statically dispatched?
这是我的示例,假设我有一个自定义 UIView
,带有响应此功能的点击手势识别器:
func handleTap(tap: UITapGestureRecognizer) {
println("Tap!")
}
我通常更喜欢这些是私有的,所以我将其标记为私有,但它不起作用。需要 @objc
或 dynamic
说明符,如下所示:
dynamic private func handleTap(tap: UITapGestureRecognizer) {
println("Tap!")
}
这让我相信 public 函数在添加到 objective-c 对象时默认是动态的。是这样吗?如果找到请引用参考文献。
来自Using Swift with Cocoa and Objective-C:
Requiring Dynamic Dispatch
While the @objc attribute exposes your
Swift API to the Objective-C runtime, it does not guarantee dynamic
dispatch of a property, method, subscript, or initializer. The Swift
compiler may still devirtualize or inline member access to optimize
the performance of your code, bypassing the Objective-C runtime. 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.”
Swift 编译器将尝试证明对方法的调用只能以单一实现结束。如果它能证明这一点,那么它将使用静态而不是动态调度。使用 "final" 或 "private" 关键字,以及整个模块优化,将对此有所帮助。
这是我的示例,假设我有一个自定义 UIView
,带有响应此功能的点击手势识别器:
func handleTap(tap: UITapGestureRecognizer) {
println("Tap!")
}
我通常更喜欢这些是私有的,所以我将其标记为私有,但它不起作用。需要 @objc
或 dynamic
说明符,如下所示:
dynamic private func handleTap(tap: UITapGestureRecognizer) {
println("Tap!")
}
这让我相信 public 函数在添加到 objective-c 对象时默认是动态的。是这样吗?如果找到请引用参考文献。
来自Using Swift with Cocoa and Objective-C:
Requiring Dynamic Dispatch
While the @objc attribute exposes your Swift API to the Objective-C runtime, it does not guarantee dynamic dispatch of a property, method, subscript, or initializer. The Swift compiler may still devirtualize or inline member access to optimize the performance of your code, bypassing the Objective-C runtime. 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.”
Swift 编译器将尝试证明对方法的调用只能以单一实现结束。如果它能证明这一点,那么它将使用静态而不是动态调度。使用 "final" 或 "private" 关键字,以及整个模块优化,将对此有所帮助。