NSTimerを使用しているときに問題が発生しました。 のは、私はこのアーキテクチャを持っていると仮定しましょう: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
}
}
それでは、クラスのalloc、それのユーザーを想定し、直後にそれを解放してみましょう。私のタイマーはまだ生きていて、オブジェクトも(タイマーによって作られた保持があるので)。 タイマが起動すると、[self launchAThread]
が実行され、タイマが無効化されて解放され、retainCount = 0のオブジェクトが解放されます。もう一度、オブジェクトが直ちに解放されるとします。これはクラッシュを引き起こし、私の心に正しいことを止めるために何もできません。
私は同意します、これは多くの前提ですが、誰かがすでにこの問題を抱えていて、それをどのように解決したかを知りたいのです。
読んでいただきありがとうございます。私は明確だったと思います! :)
はい私は今やっている。しかし、あなたのように、もしあれば別の方法を知りたいです:)。とにかくありがとう – delannoyk
私はライブラリを作っているので、いつでもユーザーがcleanUp関数を呼び出すことはできません。だから私の問題を解決するために、私は新しいクラスを追加しました:このクラスのユーザーであるようにスレッドとタイマーの部分を行う新しいクラスと私はクリーンアップする必要があることを知っている! – delannoyk