Runtime相关

2017-06-19  本文已影响10人  南冯
1. 当接手一个比较大的项目时,利用method Swizzle (方法交换),来快速熟悉项目,从控制台输出当前控制器的名称
+ (void)load {
    
    //我们只有在开发的时候才需要查看哪个viewController将出现
    //所以在release模式下就没必要进行方法的交换
#ifdef DEBUG
    
    //原本的viewWillAppear方法
    Method viewDidAppear = class_getInstanceMethod(self, @selector(viewDidAppear:));
    
    //需要替换成 能够输出日志的viewWillAppear
    Method logViewWillAppear = class_getInstanceMethod(self, @selector(logViewWillAppear:));
    
    //两方法进行交换
    method_exchangeImplementations(viewDidAppear, logViewWillAppear);
    
#endif

}
- (void)logViewWillAppear:(BOOL)animated {
    
    NSString *className = NSStringFromClass([self class]);
    
    //在这里,你可以进行过滤操作,指定哪些viewController需要打印,哪些不需要打印
//    if ([className hasPrefix:@"UI"] == NO) {
//        NSLog(@"%@ will appear",className);
//    }
    NSLog(@"currentControllerName = %@",className);
    //下面方法的调用,其实是调用viewWillAppear
    [self logViewWillAppear:animated];
}
2. 利用关联对象为分类添加属性
@interface Person (name)
@property(nonatomic,strong)NSString *name;
@end
-(NSString *)name{
    return objc_getAssociatedObject(self, @"name");
    
}
-(void)setName:(NSString *)name{
    objc_setAssociatedObject(self, @"name", name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
上一篇下一篇

猜你喜欢

热点阅读