2010-02-04 93 views
3

我想在使用iPhone SDK 3.0的线程上运行NSTimer。我认为我正在做的一切正确(新的runloop等)。如果我呼吁viewDidDissappear [定时器无效]虽然我得到这个错误:在线程上运行NSTimer

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]; 
} 

当我删除计时器一切无效线路工作正常。我不应该使其失效或我犯了一些其他错误?

感谢

回答

7

尝试

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

代替。您将不得不制作timerThread您的视图控制器的ivar。

+0

好感谢您的帮助 – John 2010-02-04 17:07:21

0

我想你已经在“method”中完成了一些UI工作。

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

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

您可以使用块派遣的主线程或performSeletorOnMainThread工作做“方法”

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]; 
    }