如何通过扩展用一些自定义方法调配 class 的方法
how to swizzle method of class with some customized method through extension
我在玩调酒。我编写这段代码是为了交换 class 扩展方法的实现。
@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 method_exchangeImplementations not work
通过添加 dynamic 声明修饰符,混合会正确发生。如果没有这个,对 method_exchangeImplementations() 的调用不会产生预期的效果。有关动态调度的详细信息,请参阅 https://swiftunboxed.com/interop/objc-dynamic/。
像这样:
@objc dynamic func name() {
print("this is class A")
}
我在玩调酒。我编写这段代码是为了交换 class 扩展方法的实现。
@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 method_exchangeImplementations not work
通过添加 dynamic 声明修饰符,混合会正确发生。如果没有这个,对 method_exchangeImplementations() 的调用不会产生预期的效果。有关动态调度的详细信息,请参阅 https://swiftunboxed.com/interop/objc-dynamic/。
像这样:
@objc dynamic func name() {
print("this is class A")
}