我正在尝试在我的应用程序的后台运行一个计时器,我在我的应用程序中大量使用计时器,我宁愿在后台运行它,但是在尝试释放 NSAoutreleasePool 时出现内存泄漏。我的 Timer 类是单例的,所以如果我启动新计时器,旧计时器会得到释放。
+ (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];
在主线程上。我根本没有泄漏,但这会破坏拥有第二个线程的目的。
这是我的第一篇文章,我感谢任何帮助谢谢......提前......