Un délai d'attente NSThread après un certain laps de temps
Question
J'ai NSThread que je voudrais arrêter après un certain laps de temps.
[NSThread detachNewThreadSelector:@selector(someFuntion) toTarget:self withObject:nil];
- (void) someFunction {
//Some calculation that might take a long time.
//if it takes more then 10 seconds i want it to end and display a error message
}
Toute aide que vous pouvez fournir ce serait grandement apprécié.
Merci,
Zen_silence
La solution
Essayez quelque chose comme ceci:
workerThread = [[NSThread alloc] initWithTarget:self selector:@selector(someFunction) object:nil];
[workerThread start];
timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:workerThread selector:@selector(cancel) userInfo:nil repeats:NO];
Assurez-vous que vous (1) vérifier workerThread.isCancelled
quand le fil se termine pour voir si le fil a expiré, et (2) [timoutTimer invalidate]
appel à nettoyer la minuterie si le fil ne faisait pas expirer.
Autres conseils
Au lieu d'utiliser NSThread, utilisez NSOperation. Vous pouvez ensuite conserver une référence à l'opération, et définir un NSTimer pendant 10 secondes. Si les feux de minuterie, dire que l'opération elle-même annuler.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow