我的应用中有一些网络服务数据需要每 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 在我的应用程序的整个持续时间内保持活动状态?
感谢您提供的任何帮助/建议:)