2010-02-04 4 views
3

J'essaie d'exécuter un NSTimer sur un thread à l'aide de 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:Exécution de NSTimer sur un thread

bool _WebTryThreadLock(bool), 0x3986d60: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now... Program received signal: “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]; 
} 

Lorsque je supprime la ligne tout invalidant le minuteur fonctionne très bien. Est-ce que je ne suis pas censé l'invalider ou est-ce que je fais une autre erreur?

Merci

Répondre

7

Essayez

[timer performSelector:@selector(invalidate) onThread:timerThread withObject:nil waitUntilDone:NO]; 

à la place. Vous devrez faire timerThread un ivar de votre contrôleur de vue.

+0

merci Ok pour l'aide – John

0

Je suppose que vous avez fait du travail d'interface utilisateur dans "method".

timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain]; 

du 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 pour envoyer le travail sur fil conducteur ou performSeletorOnMainThread pour faire « méthode »

2
- (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]; 
    }