ios - NStimer 不会因无效而停止

标签 ios objective-c grand-central-dispatch nstimer

即使我在阅读其他链接后执行“无效”和“零”操作,我的计时器也不会停止。我的代码如下:

@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);
  }
}

关于ios - NStimer 不会因无效而停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36744774/

相关文章:

iphone - 在应用程序包中包含核心数据

ios - iOS 中另一个请求中的 HTTP 请求

ios - 使用 dispatch_semaphore 时泄漏

iphone - UIWebView 历史 If 语句

objective-c - 在 Objective C (iOS) 中拖放控件

ios - 核心数据中的计算属性

ios - 警报操作处理程序

ios - 通过多部分表单数据在服务器上发送视频

ios - 我注释掉了一个方法,但 Xcode 仍然记得它并给我一个错误

ios - 为什么 weak/strong dance 解决了这个 strong reference cycle?我不明白