我想在我的应用程序的背景中运行一个计时器,我在我的应用程序中大量使用计时器,我宁愿在后台运行它,但是在尝试释放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