Objective-C Qiqiao technology-IMS
Technical lust refers to technologies and products that are too clever and useless.
IMS refers to the Instance Method Swizzling, And the Instance Method is obfuscated.
The following code is an example of an Instance Method Swizzling and a Method Swizzling:
// Man. m-(void) run {NSLog (@ "% s, % @", _ func __, _ name) ;}- (void) jump {NSLog (@ "% s, % @", _ func __, _ name);}-(void) handsUp {NSLog (@ "% s, % @", _ func __, _ name);}-(void) handsDown {NSLog (@ "% s, % @", _ func __, _ name );} // ViewController. m-(void) viewDidLoad {... man * a = [Man manWithName: @ "a"]; Man * B = [Man manWithName: @ "B"]; [self swizzleInstanceMethodWithInstance: a originalSel: @ selector (run) replacementSel: @ selector (jump)]; [self swizzleInstanceMethodWithClass: [Man class] originalSel: @ selector (handsUp) replacementSel: @ selector (handsDown)]; [a run]; [B run]; [a handsUp]; [B handsUp];} // The output result is 23:53:39. 832 testRuntime [2196: 629365]-[Man jump], a2015-03-14 23:53:39. 833 testRuntime [2196: 629365]-[Man run], b2015-03-14 23:53:39. 833 testRuntime [2196: 629365]-[Man handsDown], a2015-03-14 23:53:39. 833 testRuntime [2196: 629365]-[Man handsDown], B
Why is the run method replaced by object a and the handsUp method?
Let's first look at how the common Method Swizzling is implemented.
-(Void) Comment :( Class) clazz originalSel :( SEL) original replacementSel :( SEL) replacement {Method a = claim (clazz, original); Method B = class_getInstanceMethod (clazz, replacement ); // class_addMethod adds a new method for this class if (class_addMethod (clazz, original, method_getImplementation (B), method_getTypeEncoding (B ))) {// implementation pointer class_replaceMethod (clazz, replacement, method_getImplementation (a), method_getTypeEncoding ());} else {// implementation pointer of Two Methods for switching method_exchangeImplementations (a, B );}}
Instance Method Swizzling uses a Method similar to KVO.
First, dynamically Add a class MySubclass inherited from the original class, then modify isa of object a as a new class, and then replace the method of the new class.
- (void)swizzleInstanceMethodWithInstance:(id)object originalSel:(SEL)original replacementSel:(SEL)replacement{ Class newClass = objc_allocateClassPair([object class], "MySubclass", 0); objc_registerClassPair(newClass); Method a = class_getInstanceMethod(newClass, original); Method b = class_getInstanceMethod([object class], replacement); if (class_addMethod(newClass, original, method_getImplementation(b), method_getTypeEncoding(b))) { class_replaceMethod(newClass, replacement, method_getImplementation(a), method_getTypeEncoding(a)); } else { method_exchangeImplementations(a, b); } object_setClass(object, newClass);}