2010-02-04 100 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]; 
    }