iOS技术专题

AFNetworking源码记

2016-04-05  本文已影响181人  One9398

AFNNetworking版本 3.1

Day1 - 115Line

宏NS_DESIGNATED_INITIALIZER

关键字nullable / nonnull / _Nullable / _Nonnull

通常默认nononull行为, 则使用NS_ASSUME_NONNULL_BEGIN和NS_ASSUME_NONNULL_END宏进行整体修饰.

Block的参数申明

(returnType/void (�^)(type name, type3 name2...)) block

宏FOUNDATION_EXPORT的使用


Day2 - 215Line

正确使用KVO添加和移除监听的属性

NSStringFromSelector利用属性的get方法获得需要监听的属性名,避免手动输入属性名字符串错误问题.

[task addObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive)) options:NSKeyValueObservingOptionNew context:NULL];

[task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))];    

Block 的typedef申明

typedef returnType (^BlockName)(type name, type2 name2,..)

typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error);

解决Block中的强引用

在持有block内部对外边的已经持有的属性变量进行使用时,block会捕获该变量,也会强引用它,形成循环引用,想要避免就要先在外部进行weak引用该变量,然后在block内进行strong引用weak变量.

__weak __typeof__(task) weakTask = task;    
[self.uploadProgress setCancellationHandler:^{
    __typeof__(weakTask) strongTask = weakTask;
    [strongTask cancel];
}];

Day3 -

利用Objective-C消息的动态转发实现MethodSwizzle

static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) {
    Method originalMethod = class_getInstanceMethod(theClass, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector);
    method_exchangeImplementations(originalMethod, swizzledMethod);
}

static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) {
    return class_addMethod(theClass, selector,  method_getImplementation(method),  method_getTypeEncoding(method));
}

+ (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass {
    Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume));
    Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend));

    if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) {
        af_swizzleSelector(theClass, @selector(resume), @selector(af_resume));
    }

    if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) {
        af_swizzleSelector(theClass, @selector(suspend), @selector(af_suspend));
    }
}

断言NSAssert的使用

- (void)af_resume {
    NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
    NSURLSessionTaskState state = [self state];
    [self af_resume];
    
    if (state != NSURLSessionTaskStateRunning) {
        [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self];
    }
}

使用关键字__block修饰变量的目的

Block和__block变量都是结构体变量, __block拓展

上一篇 下一篇

猜你喜欢

热点阅读