Skip to content

AFNetworking 中如何运用 Runloop? #113

@tbfungeek

Description

@tbfungeek
  • AFNetworking
+ (void)networkRequestThreadEntryPoint:(id)__unused object {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"AFNetworking"];
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [runLoop run];
    }
}
 
+ (NSThread *)networkRequestThread {
    static NSThread *_networkRequestThread = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
        [_networkRequestThread start];
    });
    return _networkRequestThread;
}

早期版本的AFNetworking库是基于NSURLConnection实现,为了能够在后台接收delegate回调,它会创建一个空后台线程,然后为这个线程创建一个NSRunLoop,往NSRunLoop上添加一个Source1 端口,然后跑在NSDefaultRunLoopMode模式下。 这样这个线程就会成为后台常驻线程,接下来如果要在后台线程处理什么任务都可以通过NSObject performSelector:onThread: 将任务跑到这个常驻的后台线程中。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions