ios NSTimer只执行一次甚至不执行问题

今天发现一个问题,在一个按钮的点击方法中添加NSTimer,发现不会自动执行。。。

找了好久没有找到原因,但是发现一个方法可以调用,直接代码



- (IBAction)clickStarAnimation:(id)sender {     

[self.timer fire];

}

-(void)prossAdd{

   static CGFloat end = 0.25f;    //设置黄色圆环开始滚动弧度为1/4

    end += 0.01f;

    [self.proView drawProgress:end];  

  if (end >= 1) {        

[self stopTimer];  

  }

}

-(NSTimer *)addTimer{  

  if (!_timer) {  

      __weak typeof(self) weakSelf = self;      

  _timer = [NSTimer timerWithTimeInterval: 0.1f    repeats: YES block:^(NSTimer * _Nonnull timer

{                                                // 调用这个方法, 来确定是否需要刷新数据                                                [weakSelf prossAdd ];                                         

  }];    


[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

}

    return _timer;

}

这种写法发现并不执行。。。。

经过测试发现这样写能正常执行代码(怀疑是线程问题)


- (IBAction)clickStarAnimation:(id)sender {       

  [self startTimer];

}

-(void)prossAdd {   

static CGFloat end = 0.25f;     //设置黄色圆环开始滚动弧度为1/4  

  end += 0.01f;

    [self.proView drawProgress:end];  

  if (end >= 1) {      

  [self stopTimer];  

  }

}

- (void)startTimer{  

  //为了保证UI刷新在主线程中完成。

    [self performSelectorOnMainThread:@selector(startTimeroOnMainThread) withObject:nil waitUntilDone:NO];

}

#pragma -mark 初始化定时器

- (void)startTimeroOnMainThread{    

if (!_timer) {         _timer = [NSTimer scheduledTimerWithTimeInterval:1.0/3 target:self selector:@selector(prossAdd) userInfo:nil repeats:YES];         [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];     }

}

这样定时器就正常执行了

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容