iOS开发之线程永驻

先看AFN2.x中使用的线程永驻的写法:

//NSURLConnection/AFURLConnectionOperation.m
+ (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;
}

大致的步骤:
创建线程的时候执行Target,Target开启RunLoop,默认每一个线程都是有一个RunLoop的,只不过默认没有开启(主线程是会默认开启的),需要我们手动开启,所以我们先拿到这个RunLoop,然后run就可以了。但是有一个问题,运行循环RunLoop如果没有接收到事件就会退出,所以还需要添加端口或者添加定时器之后的事件来保持运行循环一直不退出,这里我们采用添加端口的方式。

具体的请看:
基于runloop的线程保活、销毁与通信
iOS-Runloop 常驻线程/性能优化

以上!

iOS开发之线程永驻_第1张图片
小七.jpg

你可能感兴趣的:(iOS开发之线程永驻)