Created
August 14, 2018 09:39
-
-
Save wzshare/78acacbf59d5c7d9ae1bd0a46f1ca0c2 to your computer and use it in GitHub Desktop.
category example code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <objc/runtime.h> | |
@implementation UIViewController (Swizzling) | |
+ (void)load { | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
Class class = [self class]; | |
// When swizzling a class method, use the following: | |
// Class class = object_getClass((id)self); | |
SEL originalSelector = @selector(viewWillAppear:); | |
SEL swizzledSelector = @selector(xxx_viewWillAppear:); | |
Method originalMethod = class_getInstanceMethod(class, originalSelector); | |
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); | |
// 判断原有类中是否有要替换的方法的实现 | |
BOOL didAddMethod = class_addMethod(class, | |
originalSelector, | |
method_getImplementation(swizzledMethod), | |
method_getTypeEncoding(swizzledMethod)); | |
if (didAddMethod) { | |
// 当前类中没有要替换方法的实现,需要在父类中去寻找 | |
// 用method_getImplementation去获取class_getInstanceMethod里面的方法实现。然后再进行class_replaceMethod来实现Swizzling。 | |
class_replaceMethod(class, | |
swizzledSelector, | |
method_getImplementation(originalMethod), | |
method_getTypeEncoding(originalMethod)); | |
} else { | |
// 当前类中有要替换方法的实现,所以可以直接进行替换 | |
method_exchangeImplementations(originalMethod, swizzledMethod); | |
} | |
}); | |
} | |
#pragma mark - Method Swizzling | |
- (void)xxx_viewWillAppear:(BOOL)animated { | |
// 不会造成死循环 | |
[self xxx_viewWillAppear:animated]; | |
NSLog(@"viewWillAppear: %@", self); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment