2015-02-09 87 views
-2
-(void)DataShow 

{ 
    for(k=1;k<=10;k++) 

    { 
     Timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self  
     selector:@selector(LabelUpdateOfTimer) userInfo:nil 
     repeats:YES]; 

     if(k>=10) 

     { 
      break; 

     } 

    } 
    [Timer invalidate]; 
    Timer=nil; 
} 

-(void)LabelUpdateOfTimer 

{ 

    NSString *temp; 
    j=j-0.1; 
    temp=[[NSString alloc]initWithFormat:@" %f",j]; 
    TimerLabel.text=temp; 
} 

在这里,我创建了一个计时器,当它执行10次,我想停止计时器,但它不停止它仍然继续。NSTimer无效不会停止计时器

+2

你实际上正在创建10个定时器。 – sbooth 2015-02-09 13:05:30

回答

5

在您的for循环内部,您将创建10个定时器,每个增量为k。如果你想让你的定时器只触发10次,你可以在定时器调用的选择器内跟踪它。

- (void) someMethod 
{ 
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES]; 
} 

- (void) timerFireMethod:(NSTimer *)timer 
{ 
    static NSInteger fireCount = 0; 

    ++fireCount; 

    if(10 <= fireCount) 
     [timer invalidate]; 

    // Do some actual work 
} 

我推荐阅读C控制结构的基本介绍,以更好地理解语言语法。

+0

非常感谢清除定时器的概念 – 2015-02-10 09:15:24

1

我会解释一下我在想什么。如果我错了,随时纠正我。

想象一下Timer变量是皮带。当你生出一只狗时,它会被绑在皮带上。并且当一个新的产卵时,皮带从旧狗被释放并且被捆绑新的一个。老狗是免费的,除非我们已经将它绑在另一个皮带上(variable),否则我们无法从这里控制或访问它。

你所做的是关闭10个NSTimer变量并将其分配给Timer变量。每次创建一个新的时,以前由Timer保存的定时器都会从变量中松开,但仍然会继续在后台运行。

然后,在for循环之外,将使最后一个循环无效(仍由Timer变量保存)。其他9将继续永远运行,除非你可以得到他们的参考,然后停止他们,你不能。摆脱循环,并启动一个计时器。并检查选择器内部调用的次数。 @sbooth的代码将会做到这一点。

希望它清楚。

+0

不错的比喻,拯救产卵狗的心理形象! – sbooth 2015-02-09 15:00:15