美文网首页iOS 学习笔记程序员
runtime在项目中的使用

runtime在项目中的使用

作者: ios_geek | 来源:发表于2016-10-25 16:07 被阅读45次
  1. 对于bug的修复来说,最烦恼的就是在众多界面中找到对应的viewController,因此耗费了大量时间。我们只需要在控制台打印出相应的控制器名就能帮我们找到对应的视图控制器了,runtime就能帮到我们了
//
//  UIViewController+Swizzling.h
//  YL-Health-RB
//
//  Created by Alex on 16/10/25.
//  Copyright © 2016年 PingAn. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIViewController (Swizzling)

@end
//
//  UIViewController+Swizzling.m
//  YL-Health-RB
//
//  Created by Alex on 16/10/25.
//  Copyright © 2016年 PingAn. All rights reserved.
//

#import "UIViewController+Swizzling.h"
#import <objc/runtime.h>

@implementation UIViewController (Swizzling)

+ (void)load
{
#ifdef DEBUG
    Method viewWillAppear = class_getInstanceMethod(self, @selector(viewWillAppear:));
    Method logViewWillAppear = class_getInstanceMethod(self, @selector(logViewWillAppear:));
    method_exchangeImplementations(viewWillAppear, logViewWillAppear);
#endif
}

- (void)logViewWillAppear:(BOOL)animated
{
    NSLog(@"========>%@ will appear",NSStringFromClass([self class]));
    [self logViewWillAppear:animated];
}

@end

2.动态的根据后台的json数据修改native用户模型数据(通过runtime遍历一个类的全部属性然后用KVC赋值)

//后台传入json字典 native传入要改变的模型对象 返回改变完属性的对象
+ (id)changeObjectPropreties:(id)object dataDic:(NSDictionary *)dic
{
    unsigned int count;
    NSMutableArray *propertiesArray = [[NSMutableArray alloc]init];
    objc_property_t *properties = class_copyPropertyList([object class], &count);
    for(int i = 0; i < count; i++)
    {
        objc_property_t property = properties[i];
        
        NSString *keyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        [propertiesArray addObject:keyName];
    }
    free(properties);
    
    for (int i = 0; i < [dic allKeys].count; i++) {
        
        NSString *key = [[dic allKeys]objectAtIndex:i];
        if ([propertiesArray containsObject:key]) {
            [object setValue:[dic objectForKey:key] forKey:key];
        }
    }
    return object;
}

相关文章

网友评论

  • 54c5ff1699a8:请问下边的类方法是写到分类中吗还是怎么使用

本文标题:runtime在项目中的使用

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