級(jí)別: ★★☆☆☆
標(biāo)簽:「iOS」「消息轉(zhuǎn)發(fā)」「null([NSNull null])」
作者: WYW
審校: QiShare團(tuán)隊(duì)
前言:
我們?cè)陂_發(fā)過程中,可能遇到服務(wù)端返回?cái)?shù)據(jù)中有null
([NSNull null])的情況,當(dāng)取到null
值掂墓,并且對(duì)null發(fā)送消息的時(shí)候,就可能出現(xiàn)翎冲,unrecognized selector sent to instance
,應(yīng)用crash的情況媳荒。
針對(duì)這種情況府适,在每次取值的時(shí)候去做判斷處理又不大合適,以前筆者在GitHub上發(fā)現(xiàn)了一個(gè)神奇的文件NullSafe:https://github.com/nicklockwood/NullSafe肺樟。把這個(gè)文件拖到項(xiàng)目中檐春,即使出現(xiàn)null
的情況,也不會(huì)報(bào)出unrecognized selector sent to instance
的問題么伯。
筆者近期分析了一下NullSafe文件疟暖,并且通過做了一個(gè)Demo:QiSafeType,筆者將通過介紹消息轉(zhuǎn)發(fā)流程
的方式田柔,揭開NullSafe神秘的面紗俐巴。
Demo(QiSafeType)消息轉(zhuǎn)發(fā)部分解讀
- 筆者將通過演示調(diào)用
QiMessage
的實(shí)例qiMessage
沒有實(shí)現(xiàn)的length
方法,演示消息轉(zhuǎn)發(fā)過程硬爆。 -
QiSafeType消息轉(zhuǎn)發(fā)效果如下:
QiMessageForwardGif.gif
QiSafeType消息轉(zhuǎn)發(fā)效果說明:
-
qiMessage
消息轉(zhuǎn)發(fā)的整個(gè)過程主要涉及的3個(gè)方法:+ (BOOL)resolveInstanceMethod:(SEL)sel
- (id)forwardingTargetForSelector:(SEL)aSelector
- (void)forwardInvocation:(NSInvocation *)anInvocation
- 其中在
+ (BOOL)resolveInstanceMethod:(SEL)sel
的時(shí)候欣舵,會(huì)有相應(yīng)的方法緩存操作,這個(gè)操作是系統(tǒng)幫我們做的缀磕。
QiSafeType消息轉(zhuǎn)發(fā)部分解析
-
首先貼一張消息轉(zhuǎn)發(fā)的圖缘圈,筆者聊到的內(nèi)容會(huì)圍繞著這張圖展開劣光。
消息轉(zhuǎn)發(fā) 下邊筆者依次分析消息轉(zhuǎn)發(fā)的過程
下文還是以
qiMessage
調(diào)用length
方法為例,分析消息轉(zhuǎn)發(fā)的過程糟把。
- (1)首先
qiMessage
在調(diào)用length
方法后绢涡,會(huì)先進(jìn)行動(dòng)態(tài)方法解析,調(diào)用+ (BOOL)resolveInstanceMethod:(SEL)sel
遣疯,我們可以在這里動(dòng)態(tài)添加方法雄可,而且如果在這里動(dòng)態(tài)添加方法成功后,系統(tǒng)會(huì)把動(dòng)態(tài)添加的length
方法進(jìn)行緩存缠犀,當(dāng)qiMessage
再次調(diào)用length
方法的時(shí)候数苫,將不會(huì)調(diào)用+ (BOOL)resolveInstanceMethod:(SEL)sel
。會(huì)直接調(diào)用動(dòng)態(tài)添加成功的length
方法辨液。 - (2)如果動(dòng)態(tài)方法解析部分我們沒有做操作虐急,或者動(dòng)態(tài)添加方法失敗了的話,會(huì)進(jìn)行
尋找備援接收者
的過程- (id)forwardingTargetForSelector:(SEL)aSelector
室梅,這個(gè)過程用于尋找一個(gè)接收者,可以響應(yīng)未知的方法aSelector
疚宇。 - (3)如果尋找備援接收者的過程中返回值為nil的話亡鼠,那么會(huì)進(jìn)入到完整的消息轉(zhuǎn)發(fā)流程中。
完整的消息轉(zhuǎn)發(fā)流程:首先創(chuàng)建NSInvocation對(duì)象敷待,把與尚未處理的那條消息有關(guān)的全部細(xì)節(jié)都封于其中间涵,此對(duì)象包含選擇子、目標(biāo)(target)及參數(shù)榜揖。在觸發(fā)NSInvocation對(duì)象時(shí)勾哩,“消息派發(fā)系統(tǒng)”(message-dispatch system)將親自出馬,把消息指派給目標(biāo)對(duì)象举哟。(摘抄自Effective Objective-C 2.0編寫高質(zhì)量iOS與OS X的52個(gè)有效方法)
- 結(jié)合
QiMessage
中的代碼對(duì)消息轉(zhuǎn)發(fā)流程進(jìn)一步分析
- (1)先看第一部分
qiMessage
在調(diào)用length
方法后思劳,會(huì)先進(jìn)行動(dòng)態(tài)方法解析,調(diào)用+ (BOOL)resolveInstanceMethod:(SEL)sel
妨猩,如果我們?cè)谶@里為qiMessage
動(dòng)態(tài)添加方法潜叛。那么也能處理消息。
相關(guān)代碼如下:
+ (BOOL)resolveInstanceMethod:(SEL)sel {
printf("%s:%s \n", __func__ ,NSStringFromSelector(sel).UTF8String);
if (sel == @selector(length)) {
BOOL addSuc = class_addMethod([self class], sel, (IMP)(length), "q@:");
if (addSuc) {
return addSuc;
}
}
return [super resolveInstanceMethod:sel];
}
class_addMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp, const char * _Nullable types) OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
參數(shù)types傳入的"q@:"分別代表:
”q“:返回值long long ;
”@“:調(diào)用方法的的實(shí)例為對(duì)象類型
“:”:表示方法
- 如有其它需要壶硅,看下圖應(yīng)該會(huì)更直觀一些
type Encodings
- (2)
qiMessage
在調(diào)用length
方法后威兜,動(dòng)態(tài)方法解析部分如果返回值為NO的時(shí)候,會(huì)尋找備援接收者庐椒,調(diào)用- (id)forwardingTargetForSelector:(SEL)aSelector
椒舵,如果我們?cè)谶@里為返回可以處理length
的接收者。那么也能處理消息约谈。
相關(guān)代碼如下:
static NSArray *respondClasses;
- (id)forwardingTargetForSelector:(SEL)aSelector {
printf("%s:%s \n", __func__ ,NSStringFromSelector(aSelector).UTF8String);
id forwardTarget = [super forwardingTargetForSelector:aSelector];
if (forwardTarget) {
return forwardTarget;
}
Class someClass = [self qiResponedClassForSelector:aSelector];
if (someClass) {
forwardTarget = [someClass new];
}
return forwardTarget;
}
- (Class)qiResponedClassForSelector:(SEL)selector {
respondClasses = @[
[NSMutableArray class],
[NSMutableDictionary class],
[NSMutableString class],
[NSNumber class],
[NSDate class],
[NSData class]
];
for (Class someClass in respondClasses) {
if ([someClass instancesRespondToSelector:selector]) {
return someClass;
}
}
return nil;
}
這里有一個(gè)不常用的API:
+ (BOOL)instancesRespondToSelector:(SEL)aSelector;
笔宿,這個(gè)API用于返回Class對(duì)應(yīng)的實(shí)例能否相應(yīng)aSelector犁钟。
- (3)
qiMessage
在調(diào)用length
方法后,動(dòng)態(tài)方法解析部分如果返回值為NO的時(shí)候措伐,尋找備援接收者的返回值為nil的時(shí)候特纤,會(huì)進(jìn)行完整的消息轉(zhuǎn)發(fā)流程。調(diào)用- (void)forwardInvocation:(NSInvocation *)anInvocation
侥加,這個(gè)過程會(huì)有一個(gè)插曲捧存,- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
,只有我們?cè)?code>- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector中返回了相應(yīng)地NSMethodSignature實(shí)例的時(shí)候担败,完整地消息轉(zhuǎn)發(fā)流程才能得以順利完成昔穴。
先聊下插曲
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
。
摘抄自文檔:This method is used in the implementation of protocols. This method is also used in situations where an NSInvocation object must be created, such as during message forwarding. If your object maintains a delegate or is capable of handling messages that it does not directly implement, you should override this method to return an appropriate method signature.
加粗部分就是適用我們當(dāng)前場景的部分提前。
這個(gè)方法也會(huì)用于消息轉(zhuǎn)發(fā)的時(shí)候吗货,當(dāng)NSInvocation對(duì)象必須創(chuàng)建的時(shí)候,如果我們的對(duì)象能夠處理沒有直接實(shí)現(xiàn)的方法狈网,我們應(yīng)該重寫這個(gè)方法宙搬,返回一個(gè)合適的方法簽名。
- 相關(guān)代碼
- (void)forwardInvocation:(NSInvocation *)anInvocation {
printf("%s:%s \n\n\n\n", __func__ ,NSStringFromSelector(anInvocation.selector).UTF8String);
anInvocation.target = nil;
[anInvocation invoke];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
NSMethodSignature *signature = [super methodSignatureForSelector:selector];
if (!signature) {
Class responededClass = [self qiResponedClassForSelector:selector];
if (responededClass) {
@try {
signature = [responededClass instanceMethodSignatureForSelector:selector];
} @catch (NSException *exception) {
}@finally {
}
}
}
return signature;
}
- (Class)qiResponedClassForSelector:(SEL)selector {
respondClasses = @[
[NSMutableArray class],
[NSMutableDictionary class],
[NSMutableString class],
[NSNumber class],
[NSDate class],
[NSData class]
];
for (Class someClass in respondClasses) {
if ([someClass instancesRespondToSelector:selector]) {
return someClass;
}
}
return nil;
}
這里有一個(gè)不常用的API:
+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector;
拓哺,這個(gè)API通過Class及給定的aSelector返回一個(gè)包含實(shí)例方法標(biāo)識(shí)描述的方法簽名實(shí)例勇垛。
> 此外對(duì)于NSInvocation的筆者發(fā)現(xiàn)一個(gè)很好玩的點(diǎn)。
仍然以`qiMessage`調(diào)用`length`方法為例士鸥。
- (void)forwardInvocation:(NSInvocation *)anInvocation中的 anInvocation的信息如下:
<NSInvocation: 0x6000025b8140>
return value: {Q} 0
target: {@} 0x60000322c360
selector: {:} length
> return value指返回值闲孤,“Q”表示返回值類型為long long類型;
> target 指的是消息的接收者烤礁,“@“標(biāo)識(shí)對(duì)象類型讼积;
> selector指的是方法,“:” 表示是方法脚仔,后邊的length為方法名勤众。
更多內(nèi)容可見下圖NSInvocation的types:
尚存疑點(diǎn)
細(xì)心的讀者可能會(huì)發(fā)現(xiàn)在首次消息轉(zhuǎn)發(fā)的時(shí)候流程并不是
+[QiMessage resolveInstanceMethod:]:length
-[QiMessage forwardingTargetForSelector:]:length
-[QiMessage forwardInvocation:]:length
而是
+[QiMessage resolveInstanceMethod:]:length
-[QiMessage forwardingTargetForSelector:]:length
+[QiMessage resolveInstanceMethod:]:length
+[QiMessage resolveInstanceMethod:]:_forwardStackInvocation:
-[QiMessage forwardInvocation:]:length
這里的第三行+[QiMessage resolveInstanceMethod:]:length
第四行+[QiMessage resolveInstanceMethod:]:_forwardStackInvocation:
筆者查看了開源源碼:NSObject.mm
相關(guān)源碼如下:
// Replaced by CF (returns an NSMethodSignature)
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
_objc_fatal("-[NSObject methodSignatureForSelector:] "
"not available without CoreFoundation");
}
- (void)forwardInvocation:(NSInvocation *)invocation {
[self doesNotRecognizeSelector:(invocation ? [invocation selector] : 0)];
}
// Replaced by CF (throws an NSException)
- (void)doesNotRecognizeSelector:(SEL)sel {
_objc_fatal("-[%s %s]: unrecognized selector sent to instance %p",
object_getClassName(self), sel_getName(sel), self);
}
筆者尚未搞清楚原因。讀者有知道的敬請(qǐng)指教鲤脏。
QiSafeType之消息轉(zhuǎn)發(fā)相關(guān)代碼
- QiSafeType消息轉(zhuǎn)發(fā)相關(guān)的代碼在QiMessage中
NSNull+QiNullSafe.m
筆者結(jié)合NullSafe:https://github.com/nicklockwood/NullSafe仿寫了一個(gè)NSNull+QiNullSafe.m决摧。
- NSNull+QiNullSafe.m能夠避免的問題有:
NSNull *null = [NSNull null];
[null performSelector:@selector(addObject:) withObject:@"QiShare"];
[null performSelector:@selector(setValue:forKey:) withObject:@"QiShare"];
[null performSelector:@selector(valueForKey:) withObject:@"QiShare"];
[null performSelector:@selector(length) withObject:nil];
[null performSelector:@selector(integerValue) withObject:nil];
[null performSelector:@selector(timeIntervalSinceNow) withObject:nil];
[null performSelector:@selector(bytes) withObject:nil];
NullSafe是怎么處理null問題
其實(shí)NullSafe處理null問題用的是消息轉(zhuǎn)發(fā)的第三部分,走的是完整地消息轉(zhuǎn)發(fā)流程凑兰。
不過我們開發(fā)過程中掌桩,如果可以的話,還是盡可能早地處理消息轉(zhuǎn)發(fā)這部分姑食,比如在動(dòng)態(tài)方法解析的時(shí)候波岛,動(dòng)態(tài)添加方法(畢竟這一步系統(tǒng)可以為我們做方法的緩存處理)。
或者是在尋找備援接收對(duì)象的時(shí)候音半,返回能夠響應(yīng)未實(shí)現(xiàn)的方法的對(duì)象则拷。
注意:相關(guān)的使用場景在測試的時(shí)候不要用贡蓖,測試的時(shí)候盡可能還是要暴露出問題的。
并且使用的時(shí)候煌茬,最好結(jié)合著異常日志上報(bào)斥铺。
參考學(xué)習(xí)資料
- NSObject.mm
- Type Encodings
- NullSafe
- Effective Objective-C 2.0編寫高質(zhì)量iOS與OS X的52個(gè)有效方法
推薦文章:
iOS 自定義拖拽式控件:QiDragView
iOS 自定義卡片式控件:QiCardView
iOS Wireshark抓包
iOS Charles抓包
初探TCP
IP、UDP初探