AFNetworking_Deep

文章写于 2018-6-24, 阅读的是 AFNetworking 3.2.1

之前看了很多别人写的文章, 是按着别人的思路学习的, 感觉以我现在水平, 可以有自己的理解了. 网上搜到的文章大部分都是主流程, 我已经比较熟悉主流程了, 这里会写一些细节

AFHTTPSessionManager.m

204

if (serializationError) {
        if (failure) {
            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
                failure(nil, serializationError);
            });
        }

        return nil;
    }

无法生成request时, AF会把失败的block放到一个并发队列(如果有的话)/主队列中. YTKNetwork初始化了这个并发队列

AFURLRequestSerialization.m

370

// 只初始化一次的静态数组, 可以这么写
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 这个数组里的属性 设置为手动触发KVO(学要手动调用willChange和didChange方法触发)

你可能感兴趣的:(AFNetworking_Deep)