runtime在项目中的使用

  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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,403评论 30 472
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,672评论 4 61
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 5,883评论 0 9
  • 说多了“买什么”,今天我们来聊聊关于“怎么买”的事。 现在,代购和海淘已经成为了我们生活中不可或缺的一部分,很多人...
    珠宝大课堂阅读 2,688评论 0 0
  • [问答02 | 你想要“进化”成什么样子?2017.05.17留言] 知道了进化,才明白长期的意义。 人类,在适应...
    早知今日阅读 1,112评论 0 1

友情链接更多精彩内容