zoukankan      html  css  js  c++  java
  • Method Swizzling

     

    [Cocoa]深入浅出Cocoa之 Method Swizzling

     

    [Cocoa]深入浅出Cocoa之 Method Swizzling

    罗朝辉(http://blog.csdn.net/kesalin)

    CC许可,转载请注明出处

    在前文深入浅出Cocoa之消息中,我简要介绍了ObjC 中消息的基本情况,包括SEL查找,缓存以及消息转发等。在本文中,我要介绍一个很有趣的技术,Method swizzling,通过这个手法,我们可以动态修改方法的实现,从而达到修改类行为的目的。当然,还有其他办法(如 ClassPosing,Category)也可以达到这个目的。ClassPosing 是针对类级别的,是重量级的手法,Category 也差不多,比较重量级,此外 Category 还无法避免下面的递归死循环(如果你的代码出现了如下形式的递归调用,应该考虑一下你的设计,而不是使用在这里介绍的 Method Swizzling 手法,:))。

    1. // Bar  
    2. //  
    3. @implementation Bar  
    4.   
    5. - (void) testMethod  
    6. {  
    7.     NSLog(@" >> Bar testMethod");  
    8. }  
    9.   
    10. @end  
    11.   
    12. // Bar(BarCategory)  
    13. //  
    14. @implementation Bar(BarCategory)  
    15.   
    16. - (void) altRecursionMethod  
    17. {  
    18.     NSLog(@" >> Bar(BarCategory) recursionMethod");  
    19.     [self altRecursionMethod];  
    20. }  
    21.   
    22. @end  

    在前文深入浅出Cocoa之消息中提到,ObjC 中的类(class)和实例(instance)都是对象,类对象有自己的类方法列表,实例对象有自己的实例方法列表,这些方法列表(struct objc_method_list)是存储在 struct objc_class 中的。每个方法列表存储近似 SEL:Method 的对,Method 是一个对象,包含方法的具体实现 impl。由此可知,我们只需要修改 SEL 对应的 Method 的 impl 既可以达到修改消息行为的目的。下面来看代码:
    1. void PerformSwizzle(Class aClass, SEL orig_sel, SEL alt_sel, BOOL forInstance)  
    2. {  
    3.     // First, make sure the class isn't nil  
    4.     if (aClass != nil) {  
    5.         Method orig_method = nil, alt_method = nil;  
    6.   
    7.         // Next, look for the methods  
    8.         if (forInstance) {  
    9.             orig_method = class_getInstanceMethod(aClass, orig_sel);  
    10.             alt_method = class_getInstanceMethod(aClass, alt_sel);  
    11.         } else {  
    12.             orig_method = class_getClassMethod(aClass, orig_sel);  
    13.             alt_method = class_getClassMethod(aClass, alt_sel);  
    14.         }  
    15.   
    16.         // If both are found, swizzle them  
    17.         if ((orig_method != nil) && (alt_method != nil)) {  
    18.             IMP temp;  
    19.   
    20.             temp = orig_method->method_imp;  
    21.             orig_method->method_imp = alt_method->method_imp;  
    22.             alt_method->method_imp = temp;  
    23.         } else {  
    24. #if DEBUG  
    25.             NSLog(@"PerformSwizzle Error: Original %@, Alternate %@",(orig_method == nil)?@" not found":@" found",(alt_method == nil)?@" not found":@" found");  
    26. #endif  
    27.         }  
    28.     } else {  
    29. #if DEBUG  
    30.         NSLog(@"PerformSwizzle Error: Class not found");  
    31. #endif  
    32.     }  
    33. }  
    34.   
    35. void MethodSwizzle(Class aClass, SEL orig_sel, SEL alt_sel)  
    36. {  
    37.     PerformSwizzle(aClass, orig_sel, alt_sel, YES);  
    38. }  
    39.   
    40. void ClassMethodSwizzle(Class aClass, SEL orig_sel, SEL alt_sel)  
    41. {  
    42.     PerformSwizzle(aClass, orig_sel, alt_sel, NO);  
    43. }  

    让我们来分析上面代码:
    1,首先,区分类方法和实例方法;
    2,取得 SEL 对应的 Method;
    3,修改 Method 的 impl,在这里是通过交换实现的。

    上面的代码是可以工作的,但还不够完善。Apple 10.5 提供了交换 Method 实现的 API: method_exchangeImplementations 。下面我们使用这个新 API,并以 NSObject category的形式给出新的实现方式:

    1. #if TARGET_OS_IPHONE  
    2. #import <objc/runtime.h>  
    3. #import <objc/message.h>  
    4. #else  
    5. #import <objc/objc-class.h>  
    6. #endif  
    7.   
    8. // NSObject (MethodSwizzlingCategory)  
    9. //  
    10. @interface NSObject (MethodSwizzlingCategory)  
    11.   
    12. + (BOOL)swizzleMethod:(SEL)origSel withMethod:(SEL)altSel;  
    13. + (BOOL)swizzleClassMethod:(SEL)origSel withClassMethod:(SEL)altSel;  
    14.   
    15. @end  
    16.   
    17. @implementation NSObject (MethodSwizzlingCategory)  
    18.   
    19. + (BOOL)swizzleMethod:(SEL)origSel withMethod:(SEL)altSel  
    20. {  
    21.     Method origMethod = class_getInstanceMethod(self, origSel);  
    22.     if (!origSel) {  
    23.         NSLog(@"original method %@ not found for class %@", NSStringFromSelector(origSel), [self class]);  
    24.         return NO;  
    25.     }  
    26.       
    27.     Method altMethod = class_getInstanceMethod(self, altSel);  
    28.     if (!altMethod) {  
    29.         NSLog(@"original method %@ not found for class %@", NSStringFromSelector(altSel), [self class]);  
    30.         return NO;  
    31.     }  
    32.       
    33.     class_addMethod(self,  
    34.                     origSel,  
    35.                     class_getMethodImplementation(self, origSel),  
    36.                     method_getTypeEncoding(origMethod));  
    37.     class_addMethod(self,  
    38.                     altSel,  
    39.                     class_getMethodImplementation(self, altSel),  
    40.                     method_getTypeEncoding(altMethod));  
    41.       
    42.     method_exchangeImplementations(class_getInstanceMethod(self, origSel), class_getInstanceMethod(self, altSel));  
    43.   
    44.     return YES;  
    45. }  
    46.   
    47. + (BOOL)swizzleClassMethod:(SEL)origSel withClassMethod:(SEL)altSel  
    48. {  
    49.     Class c = object_getClass((id)self);  
    50.     return [c swizzleMethod:origSel withMethod:altSel];  
    51. }  
    52.   
    53. @end  
     
    代码就不用多解释了,下面我们来看如何使用。先看辅助类Foo:
    Foo.h
    1. //  
    2. //  Foo.h  
    3. //  MethodSwizzling  
    4. //  
    5. //  Created by LuoZhaohui on 1/5/12.  
    6. //  Copyright (c) 2012 http://blog.csdn.net/kesalin/. All rights reserved.  
    7. //  
    8.   
    9. #import <Foundation/Foundation.h>  
    10.   
    11. // Foo  
    12. //  
    13. @interface Foo : NSObject  
    14.   
    15. - (void) testMethod;  
    16. - (void) baseMethod;  
    17. - (void) recursionMethod;  
    18.   
    19. @end  
    20.   
    21. // Bar  
    22. //  
    23. @interface Bar : Foo  
    24.   
    25. - (void) testMethod;  
    26.   
    27. @end  
    28.   
    29. // Bar(BarCategory)  
    30. //  
    31. @interface Bar(BarCategory)  
    32.   
    33. - (void) altTestMethod;  
    34. - (void) altBaseMethod;  
    35. - (void) altRecursionMethod;  
    36.   
    37. @end  

    Foo.m
    1. //  
    2. //  Foo.m  
    3. //  MethodSwizzling  
    4. //  
    5. //  Created by LuoZhaohui on 1/5/12.  
    6. //  Copyright (c) 2012 http://blog.csdn.net/kesalin/. All rights reserved.  
    7. //  
    8.   
    9. #import "Foo.h"  
    10.   
    11. // Foo  
    12. //  
    13. @implementation Foo  
    14.   
    15. - (void) testMethod  
    16. {  
    17.     NSLog(@" >> Foo testMethod");  
    18. }  
    19.   
    20. - (void) baseMethod  
    21. {  
    22.     NSLog(@" >> Foo baseMethod");  
    23. }  
    24.   
    25. - (void) recursionMethod  
    26. {  
    27.     NSLog(@" >> Foo recursionMethod");  
    28. }  
    29.   
    30. @end  
    31.   
    32. // Bar  
    33. //  
    34. @implementation Bar  
    35.   
    36. - (void) testMethod  
    37. {  
    38.     NSLog(@" >> Bar testMethod");  
    39. }  
    40.   
    41. @end  
    42.   
    43. // Bar(BarCategory)  
    44. //  
    45. @implementation Bar(BarCategory)  
    46.   
    47. - (void) altTestMethod  
    48. {  
    49.     NSLog(@" >> Bar(BarCategory) altTestMethod");  
    50. }  
    51.   
    52. - (void) altBaseMethod  
    53. {  
    54.     NSLog(@" >> Bar(BarCategory) altBaseMethod");  
    55. }  
    56.   
    57. - (void) altRecursionMethod  
    58. {  
    59.     NSLog(@" >> Bar(BarCategory) recursionMethod");  
    60.     [self altRecursionMethod];  
    61. }  
    62.   
    63. @end  
     

    下面是具体的使用示例:

     

    1. int main (int argc, const char * argv[])  
    2. {  
    3.     @autoreleasepool  
    4.     {  
    5.         Foo * foo = [[[Foo alloc] init] autorelease];  
    6.         Bar * bar = [[[Bar alloc] init] autorelease];  
    7.           
    8.         NSLog(@"========= Method Swizzling test 1 =========");  
    9.           
    10.         NSLog(@" Step 1");  
    11.         [foo testMethod];  
    12.         [bar testMethod];  
    13.         [bar altTestMethod];  
    14.           
    15.         NSLog(@" Step 2");  
    16.         [Bar swizzleMethod:@selector(testMethod) withMethod:@selector(altTestMethod)];  
    17.         [foo testMethod];  
    18.         [bar testMethod];  
    19.         [bar altTestMethod];  
    20.           
    21.         NSLog(@"========= Method Swizzling test 2 =========");  
    22.         NSLog(@" Step 1");  
    23.         [foo baseMethod];  
    24.         [bar baseMethod];  
    25.         [bar altBaseMethod];  
    26.           
    27.         NSLog(@" Step 2");  
    28.         [Bar swizzleMethod:@selector(baseMethod) withMethod:@selector(altBaseMethod)];  
    29.         [foo baseMethod];  
    30.         [bar baseMethod];  
    31.         [bar altBaseMethod];  
    32.           
    33.         NSLog(@"========= Method Swizzling test 3 =========");  
    34.         [Bar swizzleMethod:@selector(recursionMethod) withMethod:@selector(altRecursionMethod)];  
    35.         [bar recursionMethod];  
    36.     }  
    37.   
    38.     return 0;  
    39. }  

    输出结果为:注意,test 3 中调用了递归调用“自己”的方法,你能理解为什么没有出现死循环么?

     

    ========= Method Swizzling test 1 =========
    Step 1
    >> Foo testMethod
    >> Bar testMethod
    >> Bar(BarCategory) altTestMethod
    Step 2
    >> Foo testMethod
    >> Bar(BarCategory) altTestMethod
    >> Bar testMethod
    ========= Method Swizzling test 2 =========
    Step 1
    >> Foo baseMethod
    >> Foo baseMethod
    >> Bar(BarCategory) altBaseMethod
    Step 2
    >> Foo baseMethod
    >> Bar(BarCategory) altBaseMethod
    >> Foo baseMethod
    ========= Method Swizzling test 3 =========
    >> Bar(BarCategory) recursionMethod
    >> Foo recursionMethod

     

    test3 解释:在函数体 {} 之间的部分是真正的 IMP,而在这之前的是 SEL。通常情况下,SEL 是与 IMP 匹配的,但在 swizzling 之后,情况就不同了。下图就是调用的时序图。

     

    rentzsch 写了一个完善的开源类 jrswizzle 来处理 Method Swizzling,如果你在工程中使用到 Method Swizzling手法,应该优先使用这个类库,:)。

     

    Refference

    MethodSwizzlinghttp://www.cocoadev.com/index.pl?ExtendingClasses

    jrswizzlehttps://github.com/rentzsch/jrswizzle

     
  • 相关阅读:
    Java synchronized对象级别与类级别的同步锁
    java并发编程JUC第十二篇:AtomicInteger原子整型
    java并发编程JUC第十一篇:如何在线程之间进行对等数据交换
    java并发编程JUC第十篇:CyclicBarrier线程同步
    java并发编程JUC第九篇:CountDownLatch线程同步
    java并发编程工具类JUC第八篇:ConcurrentHashMap
    分享Sql性能优化的一些建议
    java并发编程工具类JUC第七篇:BlockingDeque双端阻塞队列
    java并发编程工具类JUC第六篇:SynchronousQueue同步队列
    java并发编程工具类JUC第五篇:PriorityBlockingQueue优先级队列
  • 原文地址:https://www.cnblogs.com/developer-ios/p/4948791.html
Copyright © 2011-2022 走看看