利用runtime熟悉项目架构
团队项目比较多,有时需要接手别的项目,跳转流程是怎样的,需要修改的控制器叫什么名字。。?这些都不知道,肿么办。。。
下面利用Runtime方法交换原理,可以方便的打印你所进入的控制器,方便调试。
原理简介:
方法交换,顾名思义,就是将两个方法的实现交换。例如:将A方法和B方法交换,调用A方法的时候,就会执行B方法中的代码,反之亦然。
1.SEL – 表示该方法的名称又名选择器;
2.types – 表示该方法参数的类型;
3.IMP – 指向该方法的具体实现的函数指针,也就是就是实现方法。
参考:http://nshipster.com/method-swizzling/
新建Category文件
UIViewController+SwizzleMethods.h
1 2 3 4 5 6 7 8 9 10 11 12
|
#import <UIKit/UIKit.h>
@interface UIViewController (SwizzleMethods)
@end
|
UIViewController+SwizzleMethods.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#import "UIViewController+SwizzleMethods.h" #import <objc/runtime.h>
@implementation UIViewController (Swizzle)
+ (void)load{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ SwizzlingMethods([self class], @selector(viewWillAppear:), @selector(swiz_viewWillAppear:)); }); }
void SwizzlingMethods(Class cls, SEL systemSel, SEL newSel) { Method systemMethod = class_getInstanceMethod(cls, systemSel); Method newMethod = class_getInstanceMethod(cls, newSel);
BOOL isAddMethod = class_addMethod(cls,systemSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)); if(isAddMethod){ class_replaceMethod(cls, newSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod)); }else{ method_exchangeImplementations(systemMethod, newMethod); } }
- (void)swiz_viewWillAppear:(BOOL)animated{ if ([NSStringFromClass([self class]) isEqualToString:@"UINavigationController"] || [NSStringFromClass([self class]) isEqualToString:@"UIInputWindowController"]) { return; } [self swiz_viewWillAppear:animated]; NSLog(@"✅VC->%@",[self class]); } @end
|