在线程上运行NSTimer

时间:2010-02-04 16:44:44

标签: iphone nstimer nsthread runloop

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

  

bool _WebTryThreadLock(bool),0x3986d60:尝试从主线程或Web线程以外的线程获取Web锁。这可能是从辅助线程调用UIKit的结果。现在崩溃......   程序接收信号:“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];
}

当我删除使计时器无效的行时,一切正常。我不应该让它失效或我是否犯了其他错误?

由于

3 个答案:

答案 0 :(得分:7)

尝试

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

代替。您必须将 timerThread 设为视图控制器的ivar。

答案 1 :(得分:2)

    - (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) userInfo:nil repeats:TRUE];
    [timerThread start]; 
    }

    -(void)timerStart
    {
   @autoreleasePool{
    NSRunLoop *TimerRunLoop = [NSRunLoop currentRunLoop];
    [NSTimer scheduleTimerWithInterval:0.1 target:self selector:@selector(methodName:) userInfo:nil repeat:YES];
    [TimerRunLoop run];
    }

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

答案 2 :(得分:0)

我猜你已经在“method”中完成了一些用户界面工作。

 timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];

从日志中,您似乎已经在“方法”中的“计时器”线程中完成了UI更新工作。

您可以使用块来分配主线程上的工作,或使用performSeletorOnMainThread来执行“方法”