RunLoop构造一个永远不退出的一个后台线程

核心代码

  //添加一个source到runloop中,防止runloop无线循环消耗cpu,(原理:当runloop,run的时候发现有source的时候不会退出进行挂起,等待系统的source把这个runloop叫醒就行。)
    NSPort *port=[NSMachPort port];
    [[NSRunLoop currentRunLoop] addPort:port forMode:NSDefaultRunLoopMode];

   while (![[NSThread currentThread] isCancelled]) {
        
        [[NSRunLoop currentRunLoop] run];
    }

Demo

- (void)viewDidLoad {
    [super viewDidLoad];
// 开启一个线程
    _thread = [[NSThread alloc] initWithTarget:self
                                      selector:@selector(threadFunction:) object:nil];
    [_thread start];
}

- (void)threadFunction:(id)arg
{
    NSLog(@"thread begin");
    
    NSPort *port = [NSMachPort port];
    [[NSRunLoop currentRunLoop] addPort:port
                                forMode:NSDefaultRunLoopMode];
    
    while (![[NSThread currentThread] isCancelled])
    {
        NSLog(@"runloop begin");
        [[NSRunLoop currentRunLoop] run];
        NSLog(@"runloop end");
    }
    
    NSLog(@"thread end");
}
//点击事件(将一个方法加入后台执行),(如果不加入runloop的方法,只会执行一次)
- (IBAction)onFire:(id)sender {
    [self performSelector:@selector(fireSelector:)
                 onThread:_thread
               withObject:nil
            waitUntilDone:NO];
}



- (void)fireSelector:(id)arg
{
    NSLog(@"fire in the hole");
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。