Created
August 28, 2017 03:45
-
-
Save luowei/70a1d450d53e00456857725df232a692 to your computer and use it in GitHub Desktop.
NSObject Swizzing
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
#pragma mark - Swizzling | |
#import <objc/runtime.h> | |
@interface NSObject (LWSwizzling) | |
+ (BOOL)swizzleMethod:(SEL)origSel withMethod:(SEL)altSel ; | |
+ (BOOL)swizzleClassMethod:(SEL)origSel withMethod:(SEL)altSel; | |
@end | |
@implementation NSObject (LWSwizzling) | |
+ (BOOL)swizzleMethod:(SEL)origSel withMethod:(SEL)altSel { | |
Method origMethod = class_getInstanceMethod(self, origSel); | |
Method altMethod = class_getInstanceMethod(self, altSel); | |
if (!origMethod || !altMethod) { | |
return NO; | |
} | |
class_addMethod(self,origSel,class_getMethodImplementation(self, origSel),method_getTypeEncoding(origMethod)); | |
class_addMethod(self,altSel,class_getMethodImplementation(self, altSel),method_getTypeEncoding(altMethod)); | |
method_exchangeImplementations(class_getInstanceMethod(self, origSel),class_getInstanceMethod(self, altSel)); | |
return YES; | |
} | |
+ (BOOL)swizzleClassMethod:(SEL)origSel withMethod:(SEL)altSel { | |
return [object_getClass((id)self) swizzleMethod:origSel withMethod:altSel]; | |
} | |
@end | |
//调用 | |
@implementation UINavigationController (Ext) | |
+ (void)load { | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
[self swizzleMethod:@selector(pushViewController:animated:) withMethod:@selector(myPushViewController:animated:)]; | |
}); | |
} | |
- (void)myPushViewController:(UIViewController *)myPushViewController animated:(BOOL)animated { | |
if(![self.topViewController isKindOfClass:[myPushViewController class]]){ | |
[self myPushViewController:myPushViewController animated:animated]; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment