2010-01-18 68 views
1

我想在我的應用程序的背景中運行一個計時器,我在我的應用程序中大量使用計時器,我寧願在後臺運行它,但是在嘗試釋放NSAoutreleasePool時出現內存泄漏。我的計時器類是單身人士,所以如果我開始新計時器舊計時器得到dealloc它。在NSThread中運行NSTimer?

+ (void)timerThread{ 

    timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimerThread) object:nil]; //Create a new thread 
    [timerThread start]; //start the thread 
} 

//the thread starts by sending this message 
+ (void) startTimerThread 
{ 
    timerNSPool = [[NSAutoreleasePool alloc] init]; 
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; 
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startTime:) userInfo:nil repeats:YES]; 
    //timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(startTime:) userInfo:nil repeats:YES]; 
    //[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; 
    [runLoop run]; 
    [timerNSPool release]; 
} 

+ (void)startTime:(NSTimer *)theTimer{ 

    if(timeDuration > 1) 
     timeLabel.text = [NSString stringWithFormat:@"%d",--timeDuration]; 
    else{ 
     [self stopTimer]; 
     [delegate timeIsUp]; 
    } 

} 
+ (void) stopTimer{ 

    if(timer != nil) 
    {  
     [timerThread release]; 
     [timeLabel release]; 
     [timer invalidate]; 
     timer = nil; 
    } 

} 

我從來沒有遇到過在運行應用程序autoreleasepool的主線程runLoop上運行NSTimer的問題。 我在[timerNSPool發佈]泄漏; GeneralBlock-16的malloc的WebCore WKSetCurrentGraphicsContext

什麼引起泄漏從輔助線程更新UI:

timeLabel.text = [NSString stringWithFormat:@"%d",--timeDuration]; 

但是我加入另一種方法updateTextLbl,然後我使用此

[self performSelectorOnMainThread:@selector(updateTextLbl) withObject:nil waitUntilDone:YES]; 
調用它

在主線程上。我根本沒有泄漏,但是這會破壞第二個線程的目的。

這是我的第一篇文章,我感謝所有幫助謝謝...提前....

回答

0

即興的NSRunLoop你在那裏似乎有點格格不入。從文檔:

通常,您的應用程序不需要創建或顯式管理NSRunLoop對象。每個NSThread對象(包括應用程序的主線程)都根據需要爲其自動創建一個NSRunLoop對象。如果你需要訪問當前線程的運行循環,你可以使用類方法currentRunLoop來完成。

你有一個定時器,啓動一個線程,獲取當前運行循環並嘗試開始運行它。你想把計時器和運行循環關聯起來嗎?

通過將呼叫:

(無效)addTimer:(*的NSTimer)aTimer forMode:(的NSString *)模式

+0

我沒有創建任何NSRunLoop我只是獲取當前循環的引用,它是當前線程運行循環。 – Unis 2010-01-18 13:47:39

2

您正在更新您的UI +startTime:,但該方法不會在主線程中運行。這可能是您看到的WebCore警告的來源。

+0

其實這可能是這種情況,謝謝。任何想法如何嘗試從輔助線程更新我的用戶界面,而不會運行到此內存泄漏? – Unis 2010-01-18 13:45:45

+0

使用-performSelectorOnMainThread:withObject:waitUntilDone :.但是,如果這就是你所有的Timer,那麼在它自己的線程中運行它就沒有意義了。 – Darren 2010-01-18 19:59:26

+0

我想讓計時器運行在自己的線程上的唯一原因是因爲我經常爲每個玩家輪流使用它,所以它在整個應用程序運行時都被使用,我也注意到在運行時與UI交互時的性能問題主線程上的計時器,這就是爲什麼我轉移到第二個線程,歡迎任何建議... – Unis 2010-01-20 04:46:04