Swift function swizzling / runtime

后端 未结 8 1185
自闭症患者
自闭症患者 2020-12-05 08:04

Before Swift, in Objective-C I would swizzle or hook methods in a class using .

If anyone has any info on the topic of modifying S

相关标签:
8条回答
  • 2020-12-05 08:26

    I'm answering this question more than one year later because none of the other answers provide the definitive set of requirements for method swizzling for every kind of class.

    What is described by other, while it will work flawlessly for extensions to foundation/uikit classes (like NSDictionary), will simply never work for your own Swift classes.

    As described here, there is an additional requirement for method swizzling other than extending NSObject in your custom class.

    The swift method you want to swizzle must be marked dynamic.

    If you don't mark it, the runtime will simply continue to call the original method instead of the swizzled one, even if the method pointers appear to have been swapped correctly.

    Update:

    I've expanded this answer in a blog post.

    0 讨论(0)
  • 2020-12-05 08:29

    I wouldn't do it that way, I think closures provide the answers (as they give you a chance to intercept, evaluate, and forward the invocation of the function, additionally it will be easy to extend when and if we have reflection.

    http://www.swift-studies.com/blog/2014/7/13/method-swizzling-in-swift

    0 讨论(0)
提交回复
热议问题