Proper way of method swizzling in objective-C

后端 未结 2 614
慢半拍i
慢半拍i 2020-12-08 17:44

Currently experimenting with method swizzling in Objective-C and I have a question. I am trying to understand the proper way to method swizzle and after researc

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 18:38

    In particular I am confused on the didAddMethod logic. Why is the author not just directly swapping/exchanging method implementations?

    Your confusion is understandable as this logic is not explained clearly.

    First ignore the fact that the example is a category on the specific class UIViewController and just consider the logic as though the category was on some arbitrary class, let's call that class TargetClass.

    We'll call the existing method we wish to replace existingMethod.

    The category, being on TargetClass, adds the swizzling method, which we'll call swizzlingMethod, to TargetClass.

    Important: Note that the function to get an method, class_getInstanceMethod, will find the method in the supplied class or any of its superclasses. However the functions class_addMethod and class_replaceMethod only add/replace methods in the supplied class.

    Now there are two cases to consider:

    1. TargetClass itself directly contains an implementation of existingMethod. This is the easy case, all that needs to be done is exchange the implementations of existingMethod and swizzlingMethod, which can be done with method_exchangeImplementations. In the article the call to class_addMethod will fail, as there is already and existingMethod directly in TargetClass and the logic results in a call to method_exchangeImplementations.

    2. TargetClass does not directly contain an implementation of existingMethod, rather that method is provided through inheritance from one of the ancestor classes of TargetClass. This is the trickier case. If you simply exchange the implementations of existingMethod and swizzlingMethod then you would be effecting (instances of) the ancestor class (and in a way which could cause a crash - why is left as an exercise). By calling class_addMethod the article's code makes sure there is an existingMethod in TargetClass - the implementation of which is the original implementation of swizzlingMethod. The logic then replaces the implementation of swizzlingMethod with the implementation of the ancestor's existingMethod (which has no effect on the ancestor).

    Still here? I hope that makes sense and hasn't simply sent you cross-eyed!

    Another exercise if you're terminally curious: Now you might ask what happens if the ancestor's existingMethod implementation contains a call to super... if the implementation is now also attached to swizzlingMethod in TargetClass where will that call to super end up? Will it be to implementation in ancestor, which would see the same method implementation executed twice, or to the ancestor's ancestor, as originally intended?

    HTH

提交回复
热议问题