美文网首页
Runtime相关

Runtime相关

作者: 南冯 | 来源:发表于2017-06-19 14:23 被阅读10次
    1. 当接手一个比较大的项目时,利用method Swizzle (方法交换),来快速熟悉项目,从控制台输出当前控制器的名称
    • 创建 UIViewcontroller 的一个分类
    • 引入头文件 #import <objc/runtime.h>
    • 在load方法中将自定义的logViewWillAppear方法与系统的viewWillAppear 方法进行交换
    + (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
    
    }
    
    • 自定义logViewWillAppear
    - (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);
    }
    

    相关文章

      网友评论

          本文标题:Runtime相关

          本文链接:https://www.haomeiwen.com/subject/mpvgqxtx.html