保持包含NSTimer的NSThread无限期?(苹果手机)

Ric*_*kiG 1 iphone nstimer nsthread

我的应用程序中有一些Web服务数据需要每3分钟更新一次.我曾尝试过一些方法,但上周在这里得到了一个非常好的建议,我不应该每隔3分钟建立一个新线程然后尝试dealloc并同步所有不同的部分,以便我避免内存错误.相反,我应该有一个始终在运行的"工作线程",但只在我提出要求时才进行实际工作(每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];
}
Run Code Online (Sandbox Code Playgroud)

好的,这会在"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...");

}
Run Code Online (Sandbox Code Playgroud)

我之前从未使用过这样的线程.我一直都是"设置autoReleasePool,做好工作,让你的autoReleasePool耗尽,再见".

我的问题是,一旦initWithTimerInterval运行NSThread完毕,它就会返回到updateModel方法并将其池耗尽.我想这与NSTimer有自己的线程/ runloop有关吗?我想让线程继续testIfUpdateNeeded每隔3分钟运行一次方法.

那么如何在我的应用程序的整个过程中保持这个NSThread活着?

感谢您给予的任何帮助/建议:)

Ken*_*agh 5

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

[[NSRunLoop currentRunLoop] run];
Run Code Online (Sandbox Code Playgroud)

该线程将无限期地运行其运行循环,您的计时器将起作用.