我在玩嗖嗖的游戏。我编写这段代码是为了交换带有扩展的类的方法的实现。
@objc class A: NSObject {
@objc func name() {
print("this is class A")
}
}
extension A {
@objc func myName() {
self.myName()
print("this is my extension version of A")
}
}
@objc class B: A {
@objc override func name() {
super.name()
}
@objc override func myName() {
super.myName()
}
}
// swizzling name and myName
let originalSelector = #selector(A.name)
let swizzledSelector = #selector(A.myName)
guard let swizzledMethod = class_getInstanceMethod(A.self, swizzledSelector) else {
fatalError()
}
if let originalMethod = class_getInstanceMethod(A.self, originalSelector) {
method_exchangeImplementations(originalMethod, swizzledMethod)
print("replaced")
}
现在我运行这个代码来测试它:
let b = B()
print("-----")
b.name()
print("-----")
b.myName()
我期望这个输出:
replaced
-----
this is class A
this is my extension version of A
-----
this is class A
但我在日志中实际看到的是:
replaced
-----
this is class A
-----
this is class A
我做错了什么?
参考swift方法_exchangeImplementations不起作用
通过添加动态声明修饰符,可以正确地进行swizzling。如果没有这一点,对method_exchangeImplementations((的调用就不会产生预期效果。看见https://swiftunboxed.com/interop/objc-dynamic/有关动态调度的更多信息。
就像这样:
@objc dynamic func name() {
print("this is class A")
}