寫在前面
runtime 是底層的東西,是 OC 的根基,叫做"動態(tài)運行時",運行過程中將 OC 轉(zhuǎn)化為 C,在程序運行時候提供服務(wù),如果消息傳遞,動態(tài)添加屬性,動態(tài)添加方法 以及重要的 KVC 的dictionary轉(zhuǎn) model.
程序??必啃的骨頭,來一起下嘴,啃~~
一,使用 runtime 進(jìn)行 KVC 映射賦值
KVC 的實現(xiàn)原理為在 model 中查找相應(yīng)的方法進(jìn)行賦值,順序如下:
如果上面的圖(微信隨便畫了一個??)無法理解,就看下面的一幅圖.由于 簡書的Markdown 還不支持流程圖,無法得到正常的流程圖,就在別的編輯器寫好,截取過來了
附上 Markdown語法如下:
st=>start: Start
cond=>condition: 查找 setValue
cond2=>condition: 查找 _value
cond3=>condition: 查找 value
sub=>subroutine: KVC 轉(zhuǎn)換為 model
e=>end
st->cond
cond(no)->cond2(no)->cond3
cond(yes)->sub->e
cond2(yes)->sub->e
cond3(yes)->sub->e
明白了這個,就開始寫代碼.
創(chuàng)建 NSObject 的 Category, 定義類方法
.h
//
// NSObject+CategoryOfNSObject.h
// Runtime
//
// Created by 宋金委 on 2016/10/21.
// Copyright ? 2016年 song. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSObject (CategoryOfNSObject)
/**
初始化一個 Model
@param dict 字典
*/
+(instancetype)initModelWithDictionary:(NSDictionary *)dict;
@end
.m
//
// NSObject+CategoryOfNSObject.m
// Runtime
//
// Created by 宋金委 on 2016/10/21.
// Copyright ? 2016年 song. All rights reserved.
//
#import "NSObject+CategoryOfNSObject.h"
#import <objc/runtime.h>
@implementation NSObject (CategoryOfNSObject)
+(instancetype)initModelWithDictionary:(NSDictionary *)dict{
id model = [[self alloc] init];
//變量個數(shù)
unsigned int numberOfVariable = 0;
//成員變量的數(shù)組
Ivar* ivarList = class_copyIvarList([self class], &numberOfVariable);
for (int i = 0 ; i < numberOfVariable; i++) {
Ivar singleVariable = ivarList[i];
//成員變量類型 格式:\"type\"
NSString* variableType = [NSString stringWithUTF8String:ivar_getTypeEncoding(singleVariable)];
variableType = [variableType stringByReplacingOccurrencesOfString:@"@" withString:@""];
variableType = [variableType stringByReplacingOccurrencesOfString:@"\"" withString:@""];
//成員變量名字 格式:_name
NSString* variableName = [NSString stringWithUTF8String:ivar_getName(singleVariable)];
//key "_name"-->"name"
NSString* key = [variableName substringFromIndex:1];
//獲取字典對應(yīng) key的值
id valueOfKeyInDict = dict[key];
if (![valueOfKeyInDict isKindOfClass:[NSDictionary class]] && ![variableType hasPrefix:@"NS"]) {
Class classOfVariable = NSClassFromString(variableType);
valueOfKeyInDict = [classOfVariable initModelWithDictionary:valueOfKeyInDict];
}
if(valueOfKeyInDict){
[model setValue:valueOfKeyInDict forKey:key];
}
}
//很重要
free(ivarList);
return model;
}
@end
簡單測試調(diào)用代碼
//
// ViewController.m
// Runtime
//
// Created by 宋金委 on 2016/10/20.
// Copyright ? 2016年 song. All rights reserved.
//
#import "ViewController.h"
#import "NSObject+CategoryOfNSObject.h"
#import "Model.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Model* model = [Model initModelWithDictionary:@{@"name":@"Song",@"age":@"22",@"address":@"China"}];
NSLog(@"----%@",model);
}
@end
測試結(jié)果:
二,消息機制
在 OC中調(diào)用方法時候,是被clang 編譯器 cpp,terminal可以輸入 "clang -rewrite-objc 文件名",可以生成. cpp 文件,可以看到方法調(diào)用工程中被編譯為 objc_msgSend("className","methodName");
例如:只是簡寫過后的樣子
NSArray * array = [[NSArray alloc] init];
//最底層的寫法
==> NSArray * array = objc_msgSend(getClass("NSArray"),sel_registerName("alloc"));
//另外一種方法
==> array = objc_msgSend(array,@selector(init));
應(yīng)用場景:當(dāng)某個方法沒有暴露,可以使用 obj_msgSend 調(diào)用;
方法調(diào)用工程: 編譯工程時候,會將對象的方法,轉(zhuǎn)化為方法編號,放到對象的方法列表(hash 表),在方法被調(diào)用的過程中,發(fā)送消息,通過類對象的 isa 指針查找方法是否存在,如果存在,映射對應(yīng)的方法編號,在代碼區(qū)查找對應(yīng)的實現(xiàn),調(diào)用方法.
三,替換方法
//
// NSMutableArray+CategoryOfNSMutableArray.m
// Runtime
//
// Created by HMC on 2016/10/24.
// Copyright ? 2016年 song. All rights reserved.
//
#import "NSMutableArray+CategoryOfNSMutableArray.h"
#import <objc/runtime.h>
@implementation NSMutableArray (CategoryOfNSMutableArray)
//第一次加載的時候執(zhí)行一次
+(void)load{
Method addObject = class_getInstanceMethod(self, @selector(addObject:));
Method song_addObject = class_getInstanceMethod(self, @selector(song_addObject:));
method_exchangeImplementations(addObject, song_addObject);
}
-(void)song_addObject:(id)anObject {
NSLog(@"插入對象不能為空");
if (anObject == nil) {
NSLog(@"插入對象不能為空");
}else{
[self song_addObject:anObject];
}
}
@end
調(diào)用代碼,
還是按原來的方法調(diào)用,替換方法只是在分類中是系統(tǒng)直接替換的.
NSMutableArray * ar = [NSMutableArray array];
NSString * s = @"123";
[ar addObject:s];
四,動態(tài)添加對象屬性
其實就是在分類中重寫該屬性的get/set 方法,在方法中使用 runtime 添加或者獲取值
//
// UIAlertView+CategoryOfUIAlertView.m
// Runtime
//
// Created by 宋金委 on 2016/10/24.
// Copyright ? 2016年 song. All rights reserved.
//
#import "UIAlertView+CategoryOfUIAlertView.h"
#import <objc/runtime.h>
@implementation UIAlertView (CategoryOfUIAlertView)
-(NSNumber *)intervalTime{
return objc_getAssociatedObject(self, @"intervalTime");
}
-(void)setIntervalTime:(NSNumber *)intervalTime{
objc_setAssociatedObject(self, @"intervalTime", intervalTime, OBJC_ASSOCIATION_ASSIGN);
}
@end
五,動態(tài)添加對象方法
應(yīng)用場景:當(dāng)一個 APP 提供增值服務(wù),比如開通會員,可以提供會員服務(wù),就會響應(yīng)相應(yīng)的方法;
實現(xiàn)原理: 當(dāng)一個 instance 通過performSelector(methodName)方法調(diào)用methodName 時,如果檢測每一個實現(xiàn)該方法就會執(zhí)行+(BOOL)resolveInstanceMethod:(SEL)sel這個類方法,我們在此方法中運用 runtime 進(jìn)行動態(tài)添加方法,反之就會 crash.
//
// User.m
// Runtime
//
// Created by 宋金委 on 2016/10/24.
// Copyright ? 2016年 song. All rights reserved.
//
#import "User.h"
#import <objc/runtime.h>
@implementation User
void VIPSeriviceImp(id self, SEL _cmd ,NSNumber* num ){
NSLog(@"您開通的是%@元的 VIP",num);
}
+(BOOL)resolveInstanceMethod:(SEL)sel{
if (sel == NSSelectorFromString(@"VIPSerivice:")) {
/**
runtime 動態(tài)添加方法
@param self 對象本身
@param sel SEL
@param IMP sel 的實現(xiàn)(C 函數(shù))
@param string C函數(shù)格式
@return BOOL
*/
class_addMethod(self, sel, (IMP)VIPSeriviceImp, "v@:@");
}
return [super resolveInstanceMethod:sel];
}
@end
動態(tài)調(diào)用方法performSelector ,會報警告??,不用管,這是編譯器的代碼檢測功能引起的.
//動態(tài)添加方法
User * user = [User new];
[user performSelector:@selector(VIPSerivice:) withObject:@10];
代碼地址: 點這里