NStimer 不会在无效时停止

NStimer does not stop on invalidate

即使我在阅读其他链接后正在执行 "invalidate" 和 "nil",我的计时器也不会停止。我的代码如下:

@property(nonatomic,strong) NSTimer *mytimer;

- (void)viewDidLoad {
[self performSelectorOnMainThread:@selector(updateProgressBar:) withObject:nil waitUntilDone:NO]; 
            <do some other work>
}

- (void) updateProgressBar :(NSTimer *)timer{
    static int count =0;
    count++;
    NSLog(@"count = %d",count);
    if(count<=10)
    {
        self.DownloadProgressBar.progress= (float)count/10.0f;
    }
    else{
        NSLog(@"invalidating timer");
        [self.mytimer invalidate];
        self.mytimer = nil;
        return;
    }
    if(count <= 10){
        NSLog(@"count = %d **",count);
        self.mytimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateProgressBar:) userInfo:nil repeats:YES];

    }
   } 

1) 即使在计数 >10 后达到无效定时器 else 条件并且计数继续递增,定时器也会无限地继续。

2) 我想在非主线程上执行此操作。我想在启动计时器后继续 viewdidload()。这该怎么做 ?

我访问了 SO 上的其他链接,我所了解的只是在计时器指针上调用 invalidate 和 nil。我仍然面临问题。谁能告诉我我在这里缺少什么以及我可以对后台线程上的 运行 updateProgressBar 做些什么并更新进度条?

不需要每次都安排一个定时器,安排一次,定时器就会每秒触发一次,例如你可以像下面那样做,

- (void)viewDidLoad
 {
   [super viewDidLoad];
   [self performSelectorOnMainThread:@selector(startTimerUpdate) withObject:nil waitUntilDone:NO]; //to start timer on main thread
 }

//hear schedule the timer 
- (void)startTimerUpdate
 {
    self.mytimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateProgressBar:) userInfo:nil repeats:YES];
 }

 - (void) updateProgressBar :(NSTimer *)timer{
   static int count =0;
   count++;
   NSLog(@"count = %d",count);
   if(count<=10)
   {
      //self.DownloadProgressBar.progress= (float)count/10.0f;
      NSLog(@"progress:%f",(float)count/10.0f);
   }
   else
   {
      NSLog(@"invalidating timer");
      [self.mytimer invalidate];
      self.mytimer = nil;
      return;
   }
   if(count <= 10){
     NSLog(@"count = %d **",count);
  }
}

我认为您正在多次安排计时器。我想10次。只需安排一次时间,或者如果需要多次时间,则按计划多次使其无效。

根据评论更新:从 viewdidload 和 addobserver 安排计时器意味着任务通知。当您的任务完成时使计时器无效。并在计时器的选择器方法中更新您的进度,因此当您使其无效时,它将自动停止进度条。

第二件事:您应该在移动另一个计时器之前使计时器失效viewcontroller,因为这个对象在失效之前一直有效。

希望这会有所帮助:)