NSTimer 简述

日常开发中,我们经常会使用到NSTimer,看是简单但有复杂!
举例下面使用NSTimer 使用出现的问题

NSThread *Thread =  [[NSThread alloc]initWithTarget:self selector:@selector(threed) object:nil];
    [Thread start];


-(void)threed
{
    NSThread *red= [NSThread currentThread];
    if ([red isMainThread]) {
        NSLog(@"MainThread");
    }else
    {
        NSLog(@"NotMainThread");
    }

  NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(test ) userInfo:nil repeats:YES];

}

-(void)test
{
NSLog(@"run");
{

//会发现timer执行了, scheduledTimerWithTimeInterval 这个方法在子线程不跑了,如果想要他执行怎么办?需要引用另一个方法:timerWithTimeInterval 把上面的换成下面这样:
 NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(test ) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run]; 
    这样就可以在子线运行了!

scheduledTimerWithTimeInterval,这个方法是自动回放入到默认的runloop中,除了主线程之外,其他线程的NSRunloop只有在调用[NSRunloop currentRunloop]才会创建。如有不对 请指点 !

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值