iOS-常驻线程实现以及优雅退出方式

RunLoop的开启方式:

    - (void)run;
    //使线程进入死循环,不利于控制线程退出,不推荐
    - (void)runUntilDate:(NSDate *)limitDate;
    //可以设置超时时间,在runloop处理完毕或者超时结束,可以选择重新开启runloop,优于上面的方式
    - (BOOL)runMode:(NSRunLoopMode)mode beforeDate:(NSDate *)limitDate;
    //除了时间设置外还可以设置runloop的运行模式,推荐

runloop的run调用方式:

public func run(){
    //外层循环
    while run(mode: .default, before:Date.distantFuture){ }
}

//默认运行runloop的kCFRunLoopDefaultMode
//内存循环
void CFRunLoopRun(void) {	/* DOES CALLOUT */
    int32_t result;
    do {
        //默认在kCFRunLoopDefaultMode下运行runloop
        result = CFRunLoopRunSpecific(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 1.0e10, false);
        CHECK_FOR_FORK();
    } while (kCFRunLoopRunStopped != result && kCFRunLoopRunFinished != result);
}

 

RunLoop的退出方式:

    CFRunLoopStop(CFRunLoopGetCurrent());//结束内层循环

    while (!_showStopRunLoopRun && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
    //showStopRunLoopRun自己设置的变量,控制是否退出

部分代码实现:


- (void)viewDidLoad {
    [super viewDidLoad];
    _thread = [[NSThread alloc] initWithTarget:self selector:@selector(runTest) object:nil];
    _port = [[NSPort alloc] init];
    _showStopRunLoopRun = false;
    [_thread start];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
        [self performSelector:@selector(test) onThread:_thread withObject:nil waitUntilDone:false];
}

-(void)test{
    NSLog(@"-----Current Thread is %@", [NSThread currentThread]);
}

-(void)runTest{
    [[NSRunLoop currentRunLoop] addPort:_port forMode: NSDefaultRunLoopMode];
    //设置runLoop开启两秒调用退出方法退出runloop    
    [self performSelector:@selector(removeRunLoop) withObject:nil afterDelay:2];
    
    //外层循环打破方式
    while (!_showStopRunLoopRun && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
    //当runloop退出时打印
    NSLog(@"退出runLoop");
}

-(void)removeRunLoop{
    _showStopRunLoopRun = true;
    CFRunLoopStop(CFRunLoopGetCurrent());//结束内层循环
}

 

你可能感兴趣的:(iOS开发)