美文网首页
iOS 停止子线程Runloop

iOS 停止子线程Runloop

作者: 言霏 | 来源:发表于2019-03-18 09:25 被阅读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/

    相关文章

      网友评论

          本文标题:iOS 停止子线程Runloop

          本文链接:https://www.haomeiwen.com/subject/uuimmqtx.html