我正在尝试在应用程序的后台运行计时器,我在应用程序中大量使用计时器,并且我宁愿在后台运行它,但是在尝试释放 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;
}
}
我在使用应用程序自动释放池的主线程 runLoop 上运行 NSTimer 从来没有遇到过问题。
我在 [timerNSPool release] 处遇到泄漏;
GeneralBlock-16 Malloc WebCore WKSetCurrentGraphicsContext
导致泄漏的原因是从辅助线程更新 UI:
timeLabel.text = [NSString stringWithFormat:@"%d",--timeDuration];
但是我添加了另一个方法 updateTextLbl,然后我使用这个调用它
[self performSelectorOnMainThread:@selector(updateTextLbl) withObject:nil waitUntilDone:YES];
在主线程上。我根本没有泄漏,但这将违背拥有第二个线程的目的。
这是我的第一篇文章,我感谢任何帮助,谢谢......提前......
您正在更新您的 UI+startTime:
,但该方法不在主线程中运行。这可能是您看到的 WebCore 警告的来源。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)