Swift的Swizzle黑魔法

Objective-C Category 可以隨意重寫本類的方法, Swift的Extension雖然易用, 但仍然沒有Category那樣方便的重寫方法.

但Swizzle還是可以在Extension替換掉本類的任意方法. (Swift修改CocoaPods管理的第三庫福音) 目前Swift3對于這個并不友好.

參考文章: 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)用方法的時候是直接訪問內(nèi)存, 而不是在運行時查找地址, 意味著普通的方法, 你需要在方法前加dynamic修飾字, 告訴編譯器跳過優(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

----------我是分割線---------------------------------------------

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 作者通過主人公的視角和心理活動,展現(xiàn)了一副中國六七十年代大多數(shù)農(nóng)村家庭的樣子。 作者在原生家庭生活...
    eagle0736閱讀 369評論 0 0
  • 分享 錯誤 把好東西跟別人分享 正確 把自己的好東西跟別人分享 個人財富自由 個人不需要為了滿足生活所需而出售自己...
    花溪路之風(fēng)清揚閱讀 233評論 0 0
  • 我想,我欠大家一個道歉,嗯,對,一個道歉~ 因為主編的信任,我在第四期寫作訓(xùn)練營裏,被冠以助教的名字。大約是因為我...
    珉二少閱讀 253評論 18 2