As Martin says, objc_msgSendSuper 在 Swift 中不可用,因为它是一个 C 可变参数函数,由于缺乏类型安全性,Swift 不会导入它。
另一种方法是使用class_getMethodImplementation 来获取指向函数的指针,以调用给定类类型上的选择器。从那里,您可以将其转换为 Swift 可以使用 unsafeBitCast 调用的函数类型,注意参数和返回类型匹配。
例如:
import Foundation
class C {
@objc func foo() {
print("C's foo")
}
}
class D : C {
override func foo() {
print("D's foo")
}
}
let d = D()
let superclass: AnyClass = class_getSuperclass(type(of: d))!
let selector = #selector(C.foo)
// The function to call for a message send of "foo" to a `C` object.
let impl = class_getMethodImplementation(superclass, selector)!
// @convention(c) tells Swift this is a bare function pointer (with no context object)
// All Obj-C method functions have the receiver and message as their first two parameters
// Therefore this denotes a method of type `() -> Void`, which matches up with `foo`
typealias ObjCVoidVoidFn = @convention(c) (AnyObject, Selector) -> Void
let fn = unsafeBitCast(impl, to: ObjCVoidVoidFn.self)
fn(d, selector) // C's foo
请注意,与objc_msgSendSuper 一样,它假定桥接到 Obj-C 的返回类型与指针的布局兼容。在大多数情况下(包括您的情况)都是如此,但对于返回诸如 CGRect 之类的类型的方法则不正确,该类型在 Obj-C 中使用 C 结构类型表示。
对于这些情况,您需要改用class_getMethodImplementation_stret:
import Foundation
class C {
@objc func bar() -> CGRect {
return CGRect(x: 2, y: 3, width: 4, height: 5)
}
}
class D : C {
override func bar() -> CGRect {
return .zero
}
}
let d = D()
let superclass: AnyClass = class_getSuperclass(type(of: d))!
let selector = #selector(C.bar)
let impl = class_getMethodImplementation_stret(superclass, selector)!
typealias ObjCVoidVoidFn = @convention(c) (AnyObject, Selector) -> CGRect
let fn = unsafeBitCast(impl, to: ObjCVoidVoidFn.self)
let rect = fn(d, selector)
print(rect) // (2.0, 3.0, 4.0, 5.0)
class_getMethodImplementation 和class_getMethodImplementation_stret 之间的区别在于调用约定的不同——字大小的类型可以通过寄存器传回,但是更大的结构需要间接传回。这对class_getMethodImplementation 很重要,因为它可以在对象不响应选择器的情况下传回用于消息转发的 thunk。
另一种选择是使用method_getImplementation,它不执行消息转发,因此不需要区分stret和non-stret。
例如:
let impl = method_getImplementation(class_getInstanceMethod(superclass, selector)!)
但请记住,the documentation notes:
class_getMethodImplementation 可能比method_getImplementation(class_getInstanceMethod(cls, name)) 快。