Wednesday 15 March 2017

Method swizzling in Objective C : Switching "existing selectors" implementation at runtime


Swizzling : Allows switching "existing selectors" implementation at runtime with "other selector"

Declaration:
void method_exchangeImplementations(Method m1, Method m2);

Swizzling allows you to write code that can be executed before or after 
the original method is implemented.


Example: Creating Log method for tracking view controller appearing.

#import "UIViewController+Log.h" @implementation UIViewController (Log) + (void)load { static dispatch_once_t once_token; dispatch_once(&once_token, ^{ SEL viewWillAppearSelector = @selector(viewDidAppear:); SEL viewWillAppearLoggerSelector = @selector(log_viewDidAppear:); Method originalMethod = class_getInstanceMethod(self, viewWillAppearSelector); Method extendedMethod = class_getInstanceMethod(self, viewWillAppearLoggerSelector); method_exchangeImplementations(originalMethod, extendedMethod); }); } - (void) log_viewDidAppear:(BOOL)animated { [self log_viewDidAppear:animated]; NSLog(@"viewDidAppear executed for %@", [self class]); } @end