如何开启常驻线程

2019-07-11  本文已影响0人  寂寞先森666
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
        NSLog(@"1");
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSLog(@"2");
            [self performSelector:@selector(test) withObject:nil afterDelay:3];
            NSLog(@"3");
        });
        NSLog(@"4");
}
-(void)test
{
    NSLog(@"5");
}

2019-07-11 15:13:13.212408+0800 信号量[4091:635063] 1
2019-07-11 15:13:13.213029+0800 信号量[4091:635063] 4
2019-07-11 15:13:13.213803+0800 信号量[4091:635104] 2
2019-07-11 15:13:13.214460+0800 信号量[4091:635104] 3

可以看出test方法并没有执行,因为该线程已经释放了, 所以要正常执行的话必须保活该线程

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
        NSLog(@"1");
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSLog(@"2");
            [[NSRunLoop currentRunLoop]run];//(model 添加item之前 启动)
            [self performSelector:@selector(test) withObject:nil afterDelay:3];
            NSLog(@"3");
        });
        NSLog(@"4");
}
-(void)test
{
    NSLog(@"5");
}

然而test方法依然不执行。
原因是如果RunLoop的mode中一个item都没有,RunLoop会退出。即在调用RunLoop的run方法后,由于其mode中没有添加任何item去维持RunLoop的时间循环,RunLoop随即还是会退出。
所以我们自己启动RunLoop,一定要在添加item后

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
        NSLog(@"1");
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSLog(@"2");
            [self performSelector:@selector(test) withObject:nil afterDelay:3];
            [[NSRunLoop currentRunLoop]run];//(model 添加item之后 启动)
            NSLog(@"3");
        });
        NSLog(@"4");
}
-(void)test
{
     NSLog(@"5");
}

2019-07-11 16:08:07.235156+0800 信号量[4555:687390] 1
2019-07-11 16:08:07.235340+0800 信号量[4555:687390] 4
2019-07-11 16:08:07.235351+0800 信号量[4555:687445] 2
2019-07-11 16:08:07.235687+0800 信号量[4555:687445] 3

2019-07-11 16:08:10.236961+0800 信号量[4555:687445] 5

除了添加timer 也可以这样

[[NSRunLoop currentRunLoop] addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
上一篇下一篇

猜你喜欢

热点阅读