多线程与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);

猜你喜欢

转载自blog.csdn.net/dt1991524/article/details/81383866