1

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

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

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

4

2 回答 2

2

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

于 2010-01-18T04:51:30.747 回答
0

袖手旁观,你在那里的 NSRunLoop 似乎有点不合适。从文档:

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

你有一个计时器,启动一个线程,它获取当前的运行循环并尝试开始运行它。您想将计时器与该运行循环相关联吗?

通过调用:

(void)addTimer:(NSTimer *)aTimer forMode:(NSString *)mode

?

于 2010-01-18T04:44:26.727 回答