Eta*_*tan 1 multithreading objective-c nstimer ios
我已经使用[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:]安排了一个计时器,并希望在它触发的某个时刻使它无效.
- (id)init
{
[NSTimer scheduledTimerWithInterval:1 target:self selector:@selector(fired:) userInfo:nil repeats:YES];
}
- (void)fired:(NSTimer *)timer
{
if (someCondition) {
[timer invalidate];
}
}
Run Code Online (Sandbox Code Playgroud)
这是允许的吗?文件说明
您必须从安装了计时器的线程发送此消息.如果从另一个线程发送此消息,则可能无法从其运行循环中删除与计时器关联的输入源,这可能会阻止线程正常退出.
如果这不是完成此任务的正确方法:正确的方法是什么?
[timer invalidate]
从fire方法中调用就可以了,该代码将在创建计时器时使用的线程中执行.
您引用的Apple Doc仅警告您,如果您创建一个单独的线程并使计时器无效,那么,只有这样,才会出现不可预测的行为.
防爆.
// Create the background queue
dispatch_queue_t queue = dispatch_queue_create("do not do this", NULL);
// Start work in new thread
dispatch_async(queue, ^ {
// !! do not do this !!
if (someCondition) {
[yourTimer invalidate];
}
// or this
[self fire:yourTimer];
});
// won’t actually go away until queue is empty
dispatch_release(queue);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1084 次 |
最近记录: |