Working with MethodSwizzling

What is MethodSwizzling?

Objective-C has a Nice feature named MethodSwizzling, a monkey patch is a way to extend or modify the runtime code of dynamic languages.

The Objective-C runtime lets you modify the mappings from a selector (method name) to an implementation (the method code itself). This allows you to "patch" methods in code you don't have the source to (AppKit, FoundationKit, etc). 

Unlike creating a category method with the same name as the original method (effectively replacing the original method), MethodSwizzling lets your replacement method make use of the original method, almost like subclassing.

You will get a Nice and comprehensive discussion on MethodSwizzling at http://cocoadev.com/wiki/MethodSwizzling

How to USE MethodSwizzling?

 #import <objc/runtime.h>
 #import <objc/message.h>
 //....

 void Swizzle(Class c, SEL orig, SEL new)
 {
 Method origMethod = class_getInstanceMethod(c, orig);
 Method newMethod = class_getInstanceMethod(c, new);
 if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
 class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
 else
 method_exchangeImplementations(origMethod, newMethod);
 }

What are the DANGERS of Method Swizzling in Objective-C?

Method swizzling can be used to write better, more efficient, more maintainable code. It can also be abused and lead to horrible bugs.

Here are some of the pitfalls of method swizzling:
  • Method swizzling is not atomic
  • Changes behavior of un-owned code
  • Possible naming conflicts
  • Swizzling changes the method's arguments
  • The order of swizzles matters
  • Difficult to understand (looks recursive)
  • Difficult to debug


No comments:

Post a Comment