1

我的应用中有一些网络服务数据需要每 3 分钟更新一次。我尝试了一些方法,但上周在这里得到了一个非常好的建议,我不应该每 3 分钟建立一个新线程,然后尝试释放并同步所有不同的部分,以避免内存错误。相反,我应该有一个始终在运行的“工作线程”,但只有在我要求它时才进行实际工作(每 3 分钟一次)。

由于我的小型 POC 现在可以工作,因此我在该applicationDidFinishLaunching 方法中生成了一个新线程。我这样做是这样的:

[NSThread detachNewThreadSelector:@selector(updateModel) toTarget:self withObject:nil];

- (void) updateModel {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    BackgroundUpdate *update = [[BackgroundUpdate alloc] initWithTimerInterval:180];
    [update release];
    [pool release];
}

好的,这将以秒为单位的更新间隔初始化“BackgroundUpdate”对象。在更新程序内部,现在只是这样:

@implementation BackgroundUpdate

- (id) initWithTimerInterval:(NSInteger) secondsBetweenUpdates {

    if(self = [super init]) {

        [NSTimer scheduledTimerWithTimeInterval:secondsBetweenUpdates 
                                        target:self 
                                        selector:@selector(testIfUpdateNeeded) 
                                        userInfo:nil 
                                        repeats:YES];
    }

    return self;
}

- (void) testIfUpdateNeeded {

    NSLog(@"Im contemplating an update...");

}

我以前从未使用过这样的线程。我一直在“设置 autoReleasePool,开始工作,让你的 autoReleasePool 耗尽,然后再见”。

我的问题是,一旦initWithTimerInterval运行NSThread完成,它就会返回 updateModel 方法并排空其池。我想这与 NSTimer 有它自己的线程/运行循环有关吗?我希望线程继续让该testIfUpdateNeeded方法每 3 分钟运行一次。

那么我将如何让这个 NSThread 在我的应用程序的整个持续时间内保持活动状态?

感谢您提供的任何帮助/建议:)

4

2 回答 2

5

你很近。您现在需要做的就是启动运行循环,这样线程就不会退出并且计时器会运行。在调用 initWithTimerInterval: 之后,只需调用

[[NSRunLoop currentRunLoop] run];

该线程将无限期地运行其运行循环,并且您的计时器将工作。

于 2010-02-23T15:56:21.010 回答
0

听起来您可能想要一个NSOperation而不是旧时尚线程。您可以通过通用计时器激活操作,然后它将在自己的线程上执行,然后在完成后清理自己的内存。

于 2010-02-23T14:49:55.377 回答