我在使用 NSTimer 时遇到问题。 假设我有这个架构:
ThreadedClass.m(包含一个 NSTimer* 计时器;)
- (id) init {
if (self = [super init]) {
// do blablabla
[self launchAThread];
}
return self;
}
- (void) launchAThread {
[NSThread detachNewThreadSelector:@selector(selectorToMyThreadFunction)
toTarget:self
withObject:nil];
}
- (void) selectorToMyThreadFunction {
//I do my stuff in here
//Then i relaunch a Timer to call this function
//periodically but it has to be "atomic" so no
//repeating timer since i don't know the time
//this function will take
//I do some [self changeSomething];
[self restartTimer];
//MyThread ends here (and might be recreated by the Timer's bip
}
- (void)restartTimer {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(restartTimer)
withObject:nil
waitUntilDone:NO];
return;
}
[timer invalidate];
[timer release];
timer = [[NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(launchWithTimer:)
userInfo:nil
repeats:NO] retain];
}
- (void) launchWithTimer:(NSTimer *)theTimer {
if (theTimer == timer)
{
[timer release];
timer = nil;
[self launchAThread];
}
else
{
//Nothing to be done in here, a user launch a thread manually
}
}
所以让我们假设类的用户分配它并在之后立即释放它。我的计时器仍然存在,对象也仍然存在(因为计时器进行了保留)。
当计时器触发时,它将执行 [self launchAThread]
然后计时器将失效并释放自身并且它将释放我的对象,该对象现在有一个 retainCount = 0 ...让我们假设,再时间,对象立即被释放,这将导致崩溃,我无法阻止它,这是我的想法。
我同意,这是很多假设,但我很想知道是否有人遇到过这个问题以及他是如何解决的。
感谢阅读,我希望我已经清楚了! :)
最佳答案
在释放计时器之前,您必须始终使其无效。如果计时器是 View Controller 的一部分,我总是在 viewWillDisappear 中使它无效。对我来说很奇怪 NSTimers 保留了他们的所有者。我认为最好的方法是创建 - (void)cleanUp 方法,这将使计时器无效并警告该类的用户在发布之前始终使用 cleanUp。如果有人知道更好的方法,我会很高兴。
关于objective-c - NSTimer 可能的崩溃原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9433779/