Runloop

前言:

我们会发现所有的source如果要起作用,就得加到runloop中去,如果一个runloop里面不包含任何资源的话,运行该runloop时会立马退出。APP的主线程的runloop我们没有往其中添加任何资源,为什么它还好好的运行。我们不添加,不代表框架没有添加,打印下main thread的runloop,会发现有很多资源。

 

NSRunloop只处理两种源,1.输入源 2.时间源。

输入源之下分为了:NSPort、自定义源 、performSelector:OnThread:delay:

 

举例:

1,时间源

timer需要运行是需要添加到runloop中去的

@interface ThreadCtr (){
        NSTimer *_timer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [NSThread detachNewThreadSelector:@selector(ThreadOne) toTarget:self withObject:nil];
}

 

- (void)ThreadOne{
    NSLog(@"start thread");
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(stopTimer:) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] run];
    
    NSLog(@"finish thread");
    for (int i = 0; i < 5; i ++) {
        NSLog(@"%d", i);
    }
}

上面看到_timer在用scheduledTimerWithTimeInterval方式创建的,内部已经添加到runloop里面去了,不过子线程中runloop没有默认开启, 所以加了[[NSRunLoop currentRunLoop] run];这句开启runloop,这样在子线程中才能使time起作用,然后切记 [_timer invalidate];一定要在当前线程中调用,否则time一直在运行,子线程一直存在,出现了僵尸线程。

如果使用timerWithTimerInterval来初始化timer的就需要话就需要

    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值