美文网首页
Runloop保活

Runloop保活

作者: 迷路的字母C | 来源:发表于2019-11-20 16:39 被阅读0次

初始化一个NSThread对象以后,在线程回调方法里面进行操作,调起Runloop保活

self.taskThread = [[NSThread alloc] initWithTarget:self selector:@selector(doThreadMethod) object:nil];

如果runloop在运行,是只能看到任务开始的打印

- (void)doThreadMethod
{
    NSLog(@"线程一任务开始: %@", [NSThread currentThread]);
    // 执行对应的保活方法
    [self threadKeep];
    [[NSRunLoop currentRunLoop] run];
    NSLog(@"线程一任务结束: %@", [NSThread currentThread]);
}

方法一: 添加Source1
AFNetwork用的这种方式

- (void)keepMethod01
{
    [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
}

方法二: 添加Source0

- (void)keepMethod02
{
    [self performSelector:@selector(method02Perform) onThread:[NSThread currentThread] withObject:nil waitUntilDone:NO];
}

- (void)method02Perform
{
    NSLog(@"%s", __func__);
}

方法三: 添加Timer

- (void)keepMethod03
{
    [NSTimer scheduledTimerWithTimeInterval:10 repeats:NO block:^(NSTimer * _Nonnull timer) {
        NSLog(@"%s", __func__);
    }];
}

其中方法二和方法三,按道理是已经执行完对应的方法了,Runloop里面已经没有了对应的Timer或者Source,但是测试发现这两种方法是可行的,可能与Runloop进入时机是只在entry前判断有关。

相关文章

网友评论

      本文标题:Runloop保活

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