在NSThread中运行NSTimer? [英] Running NSTimer Within an NSThread?
问题描述
我正在尝试在我的应用程序的后台运行计时器,我在我的应用程序中大量使用该计时器,而我宁愿在后台运行它,但是我在尝试释放NSAoutreleasePool时遇到内存泄漏.我的Timer类是单例,因此,如果我启动新计时器,则旧计时器会取消分配它.
I am trying to run a timer in the background of my application, i am using the timer heavily in my application and i'd rather running it in the background, However i am getting memory leaks when trying to release the NSAoutreleasePool. My Timer class is singleton, so if i start new timer the old timer get dealloc it .
+ (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
I never had a problem running the NSTimer on the main thread runLoop with application autoreleasepool. I am getting leak at [timerNSPool release]; GeneralBlock-16 Malloc WebCore WKSetCurrentGraphicsContext
导致泄漏的原因是从辅助线程更新UI:
What causing the Leak is updating UI from a secondary thread :
timeLabel.text = [NSString stringWithFormat:@"%d",--timeDuration];
但是我添加了另一个方法updateTextLbl,然后我使用它来调用它
However i added another method updateTextLbl, then i am calling it using this
[self performSelectorOnMainThread:@selector(updateTextLbl) withObject:nil waitUntilDone:YES];
在主线程上.我一点儿也没有泄漏,但这会破坏拥有第二条螺纹的目的.
on the main thread. I did not have leaks at all , but this will defeats the purpose of having a second threads.
这是我的第一篇文章,我非常感谢您的帮助.谢谢....
This my first post , and i appreciate any help Thanks... in advance....
推荐答案
您正在 + startTime:
中更新UI,但是该方法不在主线程中运行.这可能是您所看到的WebCore警告的来源.
You're updating your UI in +startTime:
, but that method does not run in the main thread. That may be the source of the WebCore warning you're seeing.
这篇关于在NSThread中运行NSTimer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!