首页 > iOS NSTimer问题

iOS NSTimer问题

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dealTimerClick) userInfo:nil repeats:YES];

一般情况下,在主线程中,创建这个定时器,dealTimerClick会正常响应。
然而,在次线程中调用这个方法,则不会响应哦。因为系统有时候的block回调并不在主线程
一般会如何解决这个问题比较好呢?
1.不管怎么样。创建定时器都采用 dispatch_async or dispatch_sync
2.在次线程中对于 self.timer增加出发代码?

[self.timer fire]//似乎是无效的

所以。定时器的知识还是很缺乏啊


    source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(_source, delay, interval * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(source, ^{
        [weakTarget fire];
    });
    dispatch_resume(source);

记得在fire方法里面加入信号量控制


[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dealTimerClick) userInfo:nil repeats:YES];
可以看下这个方法在文档中的描述:
Creates and returns a new NSTimer object and schedules it on the current run loop in the default mode.
主线程没有问题是因为主线程有自己的run loop,所以我想你在子线程上运行的时候需要自己配置下run loop。


[NSTimer timerxxx] 那个方法创建 timer ,然后:

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

楼也也讲了,是次线程中 run loop 的问题

【热门文章】
【热门文章】