我有一个内存错误,似乎可以归结为线程中发生的事情。我在解决这个问题时遇到了困难。
我有一个 UIViewController,当它处于活动状态时,即用户正在使用它的视图时,它会从 NSThread 中的 Web 服务中检索更新。
这是每 3 分钟完成一次,此延迟由以下项控制:
[self performSelector:@selector(timerDone) withObject:nil afterDelay:180.0];
该timerDone
方法现在启动检索 Web 服务数据的 NSThread 并performSelector
再次发送消息。这是一个“检查更新、填充视图、关闭一切、重复”的小程序,效果很好。
现在,用户当然可以突然点击一个按钮来加载第二个 UIViewController。发生这种情况时,我会打电话:
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timerDone) object:nil];
并在方法中进行清理dealloc
。
我现在的问题是:如果 NSThread 正在运行,而用户更改视图并开始解构这个作为 NSThread 起点的对象,会发生什么?
我是否应该保留一个 BOOL 来告诉我 NSThread 是否仍然处于活动状态,如果是这样,如果是这种情况,如何处理 NSThread。
线程是这样完成的:
- (void) runTimer {
[self performSelector:@selector(timerDone) withObject:nil afterDelay:180];
}
- (void) timerDone {
[self performSelector:@selector(runTimer) withObject:nil afterDelay:2];
[NSThread detachNewThreadSelector:@selector(updateAllVisibleElements) toTarget:self withObject:nil];
}
- (void) updateAllVisibleElements {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//call approiate web service
[pool release];
}