2010-01-18 65 views
1

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

在主线程上。我根本没有泄漏,但是这会破坏第二个线程的目的。

这是我的第一篇文章,我感谢所有帮助谢谢...提前....

回答

0

即兴的NSRunLoop你在那里似乎有点格格不入。从文档:

通常,您的应用程序不需要创建或显式管理NSRunLoop对象。每个NSThread对象(包括应用程序的主线程)都根据需要为其自动创建一个NSRunLoop对象。如果你需要访问当前线程的运行循环,你可以使用类方法currentRunLoop来完成。

你有一个定时器,启动一个线程,获取当前运行循环并尝试开始运行它。你想把计时器和运行循环关联起来吗?

通过将呼叫:

(无效)addTimer:(*的NSTimer)aTimer forMode:(的NSString *)模式

+0

我没有创建任何NSRunLoop我只是获取当前循环的引用,它是当前线程运行循环。 – Unis 2010-01-18 13:47:39

2

您正在更新您的UI +startTime:,但该方法不会在主线程中运行。这可能是您看到的WebCore警告的来源。

+0

其实这可能是这种情况,谢谢。任何想法如何尝试从辅助线程更新我的用户界面,而不会运行到此内存泄漏? – Unis 2010-01-18 13:45:45

+0

使用-performSelectorOnMainThread:withObject:waitUntilDone :.但是,如果这就是你所有的Timer,那么在它自己的线程中运行它就没有意义了。 – Darren 2010-01-18 19:59:26

+0

我想让计时器运行在自己的线程上的唯一原因是因为我经常为每个玩家轮流使用它,所以它在整个应用程序运行时都被使用,我也注意到在运行时与UI交互时的性能问题主线程上的计时器,这就是为什么我转移到第二个线程,欢迎任何建议... – Unis 2010-01-20 04:46:04