2009-08-20 5 views
1

J'utilise ce code:NSTimer problème

timer = [NSTimer scheduledTimerWithTimeInterval:2 
             target:self 
             selector:@selector(update) 
             userInfo:nil 
             repeats:YES]; 
... 

-(void)update { 
    NSDate *date = [NSDate date]; 
    NSString *Currentdate = [date descriptionWithCalendarFormat:@"%b %d, %Y %I:%M:%S %p" 
                 timeZone:nil 
                 locale:nil]; 
    lbl.text = Currentdate; 
} 

Il fonctionne très bien, mais je veux changer l'intervalle de temporisation de 2 secondes à 1 seconde au moment de l'exécution. Comment puis-je faire ceci?

Merci d'avance.

+0

scheduledTimerWithTimeInterval: 1 au lieu de 2? – diciu

+0

Je pense qu'il veut savoir comment changer l'intervalle pour le minuteur après qu'il a été créé? – jhauberg

Répondre

2

Juste invalidate l'ancien et créer un nouveau. Je ne pense pas que NSTimer prend en charge la modification de l'intervalle de temps, ce serait un cruel supplémentaire à la fois dans l'interface et la mise en œuvre.

10

Vous ne pouvez pas modifier un intervalle de temporisation après sa création.

// You have to invalidate it...be careful, 
// this releases it and will crash if done to an already invalidated timer 

if (self.timer != nil) { 
    [self.timer invalidate]; 
    self.timer = nil; 


//... then declare a new one with the different interval. 

timer = [NSTimer scheduledTimerWithTimeInterval:newInterval 
            target:self 
            selector:@selector(update) 
            userInfo:nil 
            repeats:YES]; 
}