[Cocoa] method swizzling of cocoa
Luo chaohui (http://blog.csdn.net/kesalin)
CC license. For more information, see Source
In the previous article, I briefly introduced the basic information about messages in objc, including sel search, cache, and message forwarding. In this article, I want to introduce an interesting technique, method swizzling. Through this technique, we can dynamically modify the implementation of methods to achieve the purpose of modifying class behaviors. Of course, there are other methods (such as classposing and category) to achieve this goal. Classposing
It is a heavyweight method for classification, and the category is similar and heavyweight. In addition, category cannot avoid the following recursive endless loop (If your code has the following forms of recursive calls, consider your design, instead of using the method swizzling method described here ,:)).
// Bar//@implementation Bar- (void) testMethod{ NSLog(@" >> Bar testMethod");}@end// Bar(BarCategory)//@implementation Bar(BarCategory)- (void) altRecursionMethod{ NSLog(@" >> Bar(BarCategory) recursionMethod"); [self altRecursionMethod];}@end
As mentioned in the previous article, classes and instances in objc are both objects, and class objects have their own list of class methods, the instance object has its own instance method list, which is stored in struct objc_method_list. Storage of each method list is similar to sel: Method pair. method is an object that contains the specific implementation of the method.
Impl. Therefore, we only need to modify the impl of the method corresponding to sel to modify the message behavior. Let's look at the code below:
void PerformSwizzle(Class aClass, SEL orig_sel, SEL alt_sel, BOOL forInstance){ // First, make sure the class isn't nil if (aClass != nil) { Method orig_method = nil, alt_method = nil; // Next, look for the methods if (forInstance) { orig_method = class_getInstanceMethod(aClass, orig_sel); alt_method = class_getInstanceMethod(aClass, alt_sel); } else { orig_method = class_getClassMethod(aClass, orig_sel); alt_method = class_getClassMethod(aClass, alt_sel); } // If both are found, swizzle them if ((orig_method != nil) && (alt_method != nil)) { IMP temp; temp = orig_method->method_imp; orig_method->method_imp = alt_method->method_imp; alt_method->method_imp = temp; } else {#if DEBUG NSLog(@"PerformSwizzle Error: Original %@, Alternate %@",(orig_method == nil)?@" not found":@" found",(alt_method == nil)?@" not found":@" found");#endif } } else {#if DEBUG NSLog(@"PerformSwizzle Error: Class not found");#endif }}void MethodSwizzle(Class aClass, SEL orig_sel, SEL alt_sel){ PerformSwizzle(aClass, orig_sel, alt_sel, YES);}void ClassMethodSwizzle(Class aClass, SEL orig_sel, SEL alt_sel){ PerformSwizzle(aClass, orig_sel, alt_sel, NO);}
Let's analyze the above Code:
1. First, the partition classification method and the instance method;
2. Get the method corresponding to sel;
3. Modify the impl of the method, which is implemented through switching.
The above code can work, but it is not perfect. Apple 10.5 provides an API for implementing the exchange method:method_exchangeImplementations
. Next we will use this new
API, and give a new implementation method in the form of nsobject category:
#if TARGET_OS_IPHONE#import <objc/runtime.h>#import <objc/message.h>#else#import <objc/objc-class.h>#endif// NSObject (MethodSwizzlingCategory)//@interface NSObject (MethodSwizzlingCategory)+ (BOOL)swizzleMethod:(SEL)origSel withMethod:(SEL)altSel;+ (BOOL)swizzleClassMethod:(SEL)origSel withClassMethod:(SEL)altSel;@end@implementation NSObject (MethodSwizzlingCategory)+ (BOOL)swizzleMethod:(SEL)origSel withMethod:(SEL)altSel{ Method origMethod = class_getInstanceMethod(self, origSel); if (!origSel) { NSLog(@"original method %@ not found for class %@", NSStringFromSelector(origSel), [self class]); return NO; } Method altMethod = class_getInstanceMethod(self, altSel);if (!altMethod) { NSLog(@"original method %@ not found for class %@", NSStringFromSelector(altSel), [self class]); return NO; } class_addMethod(self,origSel,class_getMethodImplementation(self, origSel),method_getTypeEncoding(origMethod));class_addMethod(self,altSel,class_getMethodImplementation(self, altSel),method_getTypeEncoding(altMethod)); method_exchangeImplementations(class_getInstanceMethod(self, origSel), class_getInstanceMethod(self, altSel));return YES;}+ (BOOL)swizzleClassMethod:(SEL)origSel withClassMethod:(SEL)altSel{ Class c = object_getClass((id)self); return [c swizzleMethod:origSel withMethod:altSel];}@end
The Code does not need to be explained much. Let's look at how to use it. Let's first look at the auxiliary class FOO:
Foo. h
//// Foo.h// MethodSwizzling//// Created by LuoZhaohui on 1/5/12.// Copyright (c) 2012 http://blog.csdn.net/kesalin/. All rights reserved.//#import <Foundation/Foundation.h>// Foo//@interface Foo : NSObject- (void) testMethod;- (void) baseMethod;- (void) recursionMethod;@end// Bar//@interface Bar : Foo- (void) testMethod;@end// Bar(BarCategory)//@interface Bar(BarCategory)- (void) altTestMethod;- (void) altBaseMethod;- (void) altRecursionMethod;@end
Foo. m
//// Foo.m// MethodSwizzling//// Created by LuoZhaohui on 1/5/12.// Copyright (c) 2012 http://blog.csdn.net/kesalin/. All rights reserved.//#import "Foo.h"// Foo//@implementation Foo- (void) testMethod{ NSLog(@" >> Foo testMethod");}- (void) baseMethod{ NSLog(@" >> Foo baseMethod");}- (void) recursionMethod{ NSLog(@" >> Foo recursionMethod");}@end// Bar//@implementation Bar- (void) testMethod{ NSLog(@" >> Bar testMethod");}@end// Bar(BarCategory)//@implementation Bar(BarCategory)- (void) altTestMethod{ NSLog(@" >> Bar(BarCategory) altTestMethod");}- (void) altBaseMethod{ NSLog(@" >> Bar(BarCategory) altBaseMethod");}- (void) altRecursionMethod{ NSLog(@" >> Bar(BarCategory) recursionMethod"); [self altRecursionMethod];}@end
The following is an example:
int main (int argc, const char * argv[]){ @autoreleasepool { Foo * foo = [[[Foo alloc] init] autorelease]; Bar * bar = [[[Bar alloc] init] autorelease]; NSLog(@"========= Method Swizzling test 1 ========="); NSLog(@" Step 1"); [foo testMethod]; [bar testMethod]; [bar altTestMethod]; NSLog(@" Step 2"); [Bar swizzleMethod:@selector(testMethod) withMethod:@selector(altTestMethod)]; [foo testMethod]; [bar testMethod]; [bar altTestMethod]; NSLog(@"========= Method Swizzling test 2 ========="); NSLog(@" Step 1"); [foo baseMethod]; [bar baseMethod]; [bar altBaseMethod]; NSLog(@" Step 2"); [Bar swizzleMethod:@selector(baseMethod) withMethod:@selector(altBaseMethod)]; [foo baseMethod]; [bar baseMethod]; [bar altBaseMethod]; NSLog(@"========= Method Swizzling test 3 ========="); [Bar swizzleMethod:@selector(recursionMethod) withMethod:@selector(altRecursionMethod)]; [bar recursionMethod]; } return 0;}
The output result is as follows: note that the "yourself" method is called recursively in Test 3. Why is there no endless loop?
======= 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 explanation: the part between function bodies {} is the real imp, and the part before this is Sel. Generally, Sel matches imp, but the situation is different after swizzling. Is the Call Sequence diagram.
Mongozsch has written a complete open-source class.
Jrswizzle is used to process method swizzling. If you use method swizzling in the project, you should first use this class library ,:).
Refference:
Methodswizzling: http://www.cocoadev.com/index.pl? Extendingclasses
Jrswizzle: https://github.com/rentzsch/jrswizzle