多线程与NSTimer

1.Ios主线程,也称UI线程,在主线程中使用NSTimer,runloop是自动开启的,(如果NSTimer当前所处的线程正在进行大数据处理(假设为一个大循环),NSTimer本次执行会等到这个大数据处理完毕之后才会继续执行(类似操作列表的滑动过程,定时器不会),所以用NSRunLoopCommonModes模式,而NSDefaultRunLoopMode不可行)。

在主线程中调用

NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(timer_callback) userInfo:nil repeats:YES];

使用NSRunLoopCommonModes模式,把timer加入到当前Run Loop中。

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

 

2.在子线程中(NSThread开辟新的子线程),使用计时器时,需要[[NSRunLoop currentRunLoop] run],(如果NSTimer当前所处的线程正在进行大数据处理(假设为一个大循环),(类似操作列表的滑动过程)使用NSDefaultRunLoopMode模式NSTimer会正常的运行。

创建并执行新的线程

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];

  [thread start];

-(void)newThread

{

@autoreleasepool {

NSTimer *timer= [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(timer_callback) userInfo:nil repeats:YES];

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

[[NSRunLoop currentRunLoop] run];

}

}

3.GCD使用定时器

//3.GCD中的Timer

uint64_t interval = 2*NSEC_PER_SEC;

dispatch_queue_t queue = dispatch_queue_create("my queue",0);

//创建Timer

_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);

dispatch_source_set_event_handler(_timer, ^{

NSLog(@"滑动时,是否走此方法");

});

dispatch_resume(_timer);

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值