文章寫于 2018-6-24, 閱讀的是 AFNetworking 3.2.1
之前看了很多別人寫的文章, 是按著別人的思路學(xué)習(xí)的, 感覺以我現(xiàn)在水平, 可以有自己的理解了. 網(wǎng)上搜到的文章大部分都是主流程, 我已經(jīng)比較熟悉主流程了, 這里會寫一些細(xì)節(jié)
AFHTTPSessionManager.m
204
if (serializationError) {
if (failure) {
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
}
return nil;
}
無法生成request時, AF會把失敗的block放到一個并發(fā)隊(duì)列(如果有的話)/主隊(duì)列中. YTKNetwork初始化了這個并發(fā)隊(duì)列
AFURLRequestSerialization.m
370
// 只初始化一次的靜態(tài)數(shù)組, 可以這么寫
static NSArray * AFHTTPRequestSerializerObservedKeyPaths() {
static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
});
return _AFHTTPRequestSerializerObservedKeyPaths;
}
觀察某個屬性名的時候, 不要寫成@"allowsCellularAccess"這種形式, 要充分利用編譯器, 這樣寫
NSStringFromSelector(@selector(allowsCellularAccess))
371
self.mutableObservedChangedKeyPaths
AF把AFHTTPRequestSerializerObservedKeyPaths里面變化的屬性都放到mutableObservedChangedKeyPaths 這里了
246
[self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
// context的正確初始化方式
static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext;
530
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
return NO;
}
return [super automaticallyNotifiesObserversForKey:key];
}
AFHTTPRequestSerializerObservedKeyPaths 這個數(shù)組里的屬性 設(shè)置為手動觸發(fā)KVO(學(xué)要手動調(diào)用willChange和didChange方法觸發(fā))