|
Answer» Method swizzling ALLOWS the implementation of an EXISTING selector to be switched at runtime for a different implementation in a classes DISPATCH table. Swizzling allows you to write code that can be executed before and/or after the ORIGINAL method. For example perhaps to track the time method execution took, or to insert log statements
#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
Method swizzling allows the implementation of an existing selector to be switched at runtime for a different implementation in a classes dispatch table. Swizzling allows you to write code that can be executed before and/or after the original method. For example perhaps to track the time method execution took, or to insert log statements #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
|