我想在我的應用程序的背景中運行一個計時器,我在我的應用程序中大量使用計時器,我寧願在後臺運行它,但是在嘗試釋放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];
調用它
在主線程上。我根本沒有泄漏,但是這會破壞第二個線程的目的。
這是我的第一篇文章,我感謝所有幫助謝謝...提前....
我沒有創建任何NSRunLoop我只是獲取當前循環的引用,它是當前線程運行循環。 – Unis 2010-01-18 13:47:39