runtime的文檔網上多的一塌糊涂东跪,細節(jié)原理就不講了
這里只是簡單整理下摸袁,平時可能會用到的一些場景
申明:
大部分代碼來自:
文/明仔Su(簡書作者): 原文鏈接
在此感謝
1.背景知識
哪里涉及到runtime
1.1 OC的方法調用流程
下面以實例對象調用方法[blackDog walk]為例描述方法調用的流程:
1幻梯、編譯器會把`[blackDog walk]`轉化為`objc_msgSend(blackDog焦除,SEL)`,SEL為@selector(walk)。
2、Runtime會在blackDog對象所對應的Dog類的方法緩存列表里查找方法的SEL
3、如果沒有找到榛斯,則在Dog類的方法分發(fā)表查找方法的SEL。(類由對象isa指針指向搂捧,方法分發(fā)表即methodList)
4驮俗、如果沒有找到,則在其父類(設Dog類的父類為Animal類)的方法分發(fā)表里查找方法的SEL(父類由類的superClass指向)
5允跑、如果沒有找到王凑,則沿繼承體系繼續(xù)下去搪柑,最終到達NSObject類。
6索烹、如果在234的其中一步中找到工碾,則定位了方法實現的入口,執(zhí)行具體實現
7百姓、如果最后還是沒有找到渊额,會面臨兩種情況:``(1) 如果是使用`[blackDog walk]`的方式調用方法````(2) 使用`[blackDog performSelector:@selector(walk)]`的方式調用方法`
1.2 消息轉發(fā)流程
1、動態(tài)方法解析
接收到未知消息時(假設blackDog的walk方法尚未實現)垒拢,runtime會調用+resolveInstanceMethod:(實例方法)或者+resolveClassMethod:(類方法)
2旬迹、備用接收者
如果以上方法沒有做處理,runtime會調用- (id)forwardingTargetForSelector:(SEL)aSelector方法求类。
如果該方法返回了一個非nil(也不能是self)的對象奔垦,而且該對象實現了這個方法,那么這個對象就成了消息的接收者尸疆,消息就被分發(fā)到該對象椿猎。
適用情況:通常在對象內部使用,讓內部的另外一個對象處理消息寿弱,在外面看起來就像是該對象處理了消息犯眠。
比如:blackDog讓女朋友whiteDog來接收這個消息
3、完整消息轉發(fā)
在- (void)forwardInvocation:(NSInvocation *)anInvocation方法中選擇轉發(fā)消息的對象脖捻,其中anInvocation對象封裝了未知消息的所有細節(jié)阔逼,并保留調用結果發(fā)送到原始調用者。
比如:blackDog將消息完整轉發(fā)給主人dogOwner來處理
2.成員變量和屬性
''你知道成員變量的本質是什么嗎地沮?"
答案在這里:OS runtime實戰(zhàn)應用:成員變量和屬性
2.1 json->model
原理描述:用runtime提供的函數遍歷Model自身所有屬性嗜浮,如果屬性在json中有對應的值,則將其賦值摩疑。
核心方法:在NSObject的分類中添加方法
- (instancetype)initWithDict:(NSDictionary *)dict {
if (self = [self init]) {
//(1)獲取類的屬性及屬性對應的類型
NSMutableArray * keys = [NSMutableArray array];
NSMutableArray * attributes = [NSMutableArray array];
/*
* 例子
* name = value3 attribute = T@"NSString",C,N,V_value3
* name = value4 attribute = T^i,N,V_value4
*/
unsigned int outCount;
objc_property_t * properties = class_copyPropertyList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
objc_property_t property = properties[i];
//通過property_getName函數獲得屬性的名字
NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
//通過property_getAttributes函數可以獲得屬性的名字和@encode編碼
NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
[attributes addObject:propertyAttribute];
}
//立即釋放properties指向的內存
free(properties);
//(2)根據類型給屬性賦值
for (NSString * key in keys) {
if ([dict valueForKey:key] == nil) continue;
[self setValue:[dict valueForKey:key] forKey:key];
}
}
return self;
}
2.2 一鍵序列化
原理描述:用runtime提供的函數遍歷Model自身所有屬性危融,并對屬性進行encode和decode操作。
核心方法:在Model的基類中重寫方法:
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
unsigned int outCount;
Ivar * ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
unsigned int outCount;
Ivar * ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
}
2.3 訪問私有變量
我們知道雷袋,OC中沒有真正意義上的私有變量和方法吉殃,要讓成員變量私有,要放在m文件中聲明楷怒,不對外暴露蛋勺。如果我們知道這個成員變量的名稱,可以通過runtime獲取成員變量鸠删,再通過getIvar來獲取它的值抱完。方法:
Ivar ivar = class_getInstanceVariable([Model class], "_str1");
NSString * str1 = object_getIvar(model, ivar);
3. 關聯對象
如何給NSArray添加一個屬性(不能使用繼承)
答案在這里:iOS runtime實戰(zhàn)應用:關聯對象
polen:
OC的分類允許給分類添加屬性,但不會自動生成getter刃泡、setter方法
所以常規(guī)的僅僅添加之后巧娱,調用的話會crash
runtime如何關聯對象
//關聯對象
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
//獲取關聯的對象
id objc_getAssociatedObject(id object, const void *key)
//移除關聯的對象
void objc_removeAssociatedObjects(id object)
應用碉怔,如何關聯:
- (void)setCustomTabbar:(UIView *)customTabbar {
//這里使用方法的指針地址作為唯一的key
objc_setAssociatedObject(self, @selector(customTabbar), customTabbar, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIView *)customTabbar {
return objc_getAssociatedObject(self, @selector(customTabbar));
}
4.Method Swizzling
method Swizzling原理
每個類都維護一個方法(Method)列表,Method則包含SEL和其對應IMP的信息禁添,方法交換做的事情就是把SEL和IMP的對應關系斷開撮胧,并和新的IMP生成對應關系
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class selfClass = object_getClass([self class]);
SEL oriSEL = @selector(imageNamed:);
Method oriMethod = class_getInstanceMethod(selfClass, oriSEL);
SEL cusSEL = @selector(myImageNamed:);
Method cusMethod = class_getInstanceMethod(selfClass, cusSEL);
BOOL addSucc = class_addMethod(selfClass, oriSEL, method_getImplementation(cusMethod), method_getTypeEncoding(cusMethod));
if (addSucc) {
class_replaceMethod(selfClass, cusSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
}else {
method_exchangeImplementations(oriMethod, cusMethod);
}
});
}
自己使用過例子:
使用場景,在iOS7中如果viewdidappear還沒有完成,就立刻執(zhí)行push或者pop操作會crash老翘,見我之前寫過的一篇文章iOS7中的pop導致的crash
解決方案就是利用method swizzing, 將系統(tǒng)的viewdidappear替換為自己重寫的sofaViewDidAppear
@implementation UIViewController (APSafeTransition)
+ (void)load
{
Method m1;
Method m2;
m1 = class_getInstanceMethod(self, @selector(sofaViewDidAppear:));
m2 = class_getInstanceMethod(self, @selector(viewDidAppear:));
method_exchangeImplementations(m1, m2);
}
|
結束:
runtime這種消息機制芹啥,并非iOS特有,其他系統(tǒng)下也有類似的東西酪捡,比如windows下的MFC等等. 這里是cocoachina下所有和runtime相關的文章叁征,請點擊查看