Exécution NSTimer sur un fil
Question
Je suis en train d'exécuter un NSTimer sur un fil en utilisant l'iPhone SDK 3.0. Je pense que je fais tout correctement (nouveau runloop etc.). Si je l'appelle [invalidate minuterie] sur viewDidDissappear si je reçois cette erreur:
bool _WebTryThreadLock (bool), 0x3986d60: a essayé d'obtenir le verrouillage de la bande à partir d'un fil autre que le fil conducteur ou le fil de la nappe. Cela peut être un résultat de l'appel à UIKit d'un fil secondaire. Crashing maintenant ... Programme signal reçu. « EXC_BAD_ACCESS »
Voici mon code:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[activityIndicator startAnimating];
NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) object:nil]; //Create a new thread
[timerThread start]; //start the thread
}
-(void)timerStart
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
//Fire timer every second to updated countdown and date/time
timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];
[runLoop run];
[pool release];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[timer invalidate];
}
Quand je retire la ligne du tout minuteur invalidant fonctionne très bien. Suis-je pas censé le rendre invalide ou que je fait une autre erreur?
Merci
La solution
Essayez
[timer performSelector:@selector(invalidate) onThread:timerThread withObject:nil waitUntilDone:NO];
au lieu. Vous devrez faire TimerThread un Ivar de votre contrôleur de vue.
Autres conseils
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) userInfo:nil repeats:TRUE];
[timerThread start];
}
-(void)timerStart
{
@autoreleasePool{
NSRunLoop *TimerRunLoop = [NSRunLoop currentRunLoop];
[NSTimer scheduleTimerWithInterval:0.1 target:self selector:@selector(methodName:) userInfo:nil repeat:YES];
[TimerRunLoop run];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
Je suppose que vous avez fait un travail d'interface utilisateur dans « method
».
timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];
Dans le journal, il semble que vous avez fait un travail de mise à jour de l'interface utilisateur dans thread « Timer » dans « méthode ».
vous pouvez utiliser le bloc à être envoyé sur le travail thread principal ou performSeletorOnMainThread
pour faire « méthode »