在线程上运行NSTimer [英] Running NSTimer on a thread

查看:82
本文介绍了在线程上运行NSTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用iPhone SDK 3.0在线程上运行NSTimer.我想我做的一切正确(新的runloop等).如果我收到此错误,但在viewDidDissappear上调用[timer invalidate],则报错:

I am trying to run a NSTimer on a thread using iPhone SDK 3.0. I think I am doing everything correctly (new runloop etc.). If I call [timer invalidate] on viewDidDissappear though I get this error:

bool _WebTryThreadLock(bool),0x3986d60:尝试从主线程或Web线程以外的线程获取Web锁.这可能是从辅助线程调用UIKit的结果.现在崩溃了... 程序接收到信号:"EXC_BAD_ACCESS".

bool _WebTryThreadLock(bool), 0x3986d60: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now... Program received signal: "EXC_BAD_ACCESS".

这是我的代码:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [activityIndicator startAnimating];
    NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) object:nil]; //Create a new thread
    [timerThread start]; //start the thread
}

-(void)timerStart
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
    //Fire timer every second to updated countdown and date/time
    timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];
    [runLoop run];
    [pool release];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [timer invalidate];
}

当我删除使计时器无效的行时,一切正常.我不应该使它无效还是犯其他错误?

When I remove the line invalidating the timer everything works fine. Am I not supposed to invalidate it or am I making some other mistake?

谢谢

推荐答案

尝试

[timer performSelector:@selector(invalidate) onThread:timerThread withObject:nil waitUntilDone:NO];

相反.您必须将 timerThread 设置为视图控制器的ivar.

instead. You will have to make timerThread an ivar of your view controller.

这篇关于在线程上运行NSTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆