iOS 停止子线程Runloop

2019-03-18  本文已影响0人  言霏

- (IBAction)startThread:(UIButton*)sender {
    self.shouldKeepRunning = YES;
    self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(runNow) object:nil];
    [self.threadstart];
}

- (void)runNow {

    self.timer = [NSTimer timerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {

        NSLog(@"timer fire");

    }];

    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:(NSDefaultRunLoopMode)];

    NSRunLoop *theRL = [NSRunLoop currentRunLoop];

    while (self.shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
}

- (IBAction)stopThread:(UIButton*)sender {

    if (self.thread && !self.thread.isFinished) {

        [self performSelector:@selector(_realStopHeartBeat) onThread:self.thread withObject:nil waitUntilDone:YES];

        [self.threadcancel];
    }
}

- (void)_realStopHeartBeat {

    if(self.timer) {

        [self.timerinvalidate];
        self.timer=nil;
    }
    CFRunLoopStop(CFRunLoopGetCurrent());

    self.shouldKeepRunning = NO;
}

或者

- (IBAction)startThread:(UIButton *)sender {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        self.shouldKeepRunning = YES;
        self.thread = [NSThread currentThread];
        self.timer = [NSTimer timerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
            NSLog(@"timer fire");
        }];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:(NSDefaultRunLoopMode)];
        NSRunLoop *theRL = [NSRunLoop currentRunLoop];
        while (self.shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
    });
}

- (IBAction)stopThread:(UIButton *)sender {
    if (self.thread && !self.thread.isFinished) {
        [self performSelector:@selector(_realStopHeartBeat) onThread:self.thread withObject:nil waitUntilDone:YES];
        
        [self.thread cancel];
    }
}

- (void)_realStopHeartBeat {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.shouldKeepRunning = NO;
}

参考:https://bestswifter.com/runloop-and-thread/

上一篇下一篇

猜你喜欢

热点阅读