Objective-C Category 可以隨意重寫(xiě)本類(lèi)的方法, Swift的Extension雖然易用, 但仍然沒(méi)有Category那樣方便的重寫(xiě)方法.
但Swizzle還是可以在Extension替換掉本類(lèi)的任意方法. (Swift修改CocoaPods管理的第三庫(kù)福音) 目前Swift3對(duì)于這個(gè)并不友好.
參考文章: Swift3 Swizzle, swift tips, Nshipster
----------我是分割線---------------------------------------------
Swift3.0 Swizzle Methods
2016.1.19
引用:
Swift code calls direct memory addresses instead of looking up method locations at runtime. This makes it possible for Swift to have better performance when doing method calls compared to Objective-C, which uses dynamic-dispatch and hence brings some overhead into each method call. The downside of this approach is, it becomes no longer possible to intercept method calls and perform some hackery.
The preferred way of of doing swizzling in Swift is using the dynamic keyword on the methods you’re gonna swizzle. Declarations marked with the dynamic modifier are also implicitly marked with the @objc attribute and dispatched using the Objective-C runtime. This means that Swift will skip the optimization of calling direct memory addresses for those methods as in Objective-C. Using the @objc attribute alone does not guarantee dynamic dispatch.
總結(jié):
Swift調(diào)用方法的時(shí)候是直接訪問(wèn)內(nèi)存, 而不是在運(yùn)行時(shí)查找地址, 意味著普通的方法, 你需要在方法前加dynamic
修飾字, 告訴編譯器跳過(guò)優(yōu)化而是轉(zhuǎn)發(fā). 否則你是攔截不到方法.
(注:viewDidLoad等方法不用加daynamic也可以截取到方法)
代碼:
class Swizzler {
dynamic func originalFunction() -> String {
return "Original function"
}
dynamic func swizzledFunction() -> String {
return "Swizzled function"
}
}
let swizzler = Swizzler()
print(swizzler.originalFunction()) // prints: "Original function"
let classToModify = Swizzler.self
let originalMethod = class_getInstanceMethod(classToModify, #selector(Swizzler.originalFunction))
let swizzledMethod = class_getInstanceMethod(classToModify, #selector(Swizzler.swizzledFunction))
method_exchangeImplementations(originalMethod, swizzledMethod)
print(swizzler.originalFunction()) // prints: "Swizzled function"
Method Swizzling in Swift
15 Tips to Become a Better Swift Developer
----------我是分割線---------------------------------------------