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.動態(tài)的根據后臺的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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容