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.

总结:

Swift调用方法的时候是直接访问内存, 而不是在运行时查找地址, 意味着普通的方法, 你需要在方法前加dynamic修饰字, 告诉编译器跳过优化而是转发. 否则你是拦截不到方法.
(注: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

----------我是分割线---------------------------------------------

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作者通过主人公的视角和心理活动,展现了一副中国六七十年代大多数农村家庭的样子。 作者在原生家庭生活...
    eagle0736阅读 374评论 0 0
  • 分享 错误 把好东西跟别人分享 正确 把自己的好东西跟别人分享 个人财富自由 个人不需要为了满足生活所需而出售自己...
    花溪路之风清扬阅读 234评论 0 0
  • 我想,我欠大家一個道歉,嗯,對,一個道歉~ 因為主編的信任,我在第四期寫作訓練營裏,被冠以助教的名字。大約是因為我...
    珉二少阅读 255评论 18 2