繁体   English   中英

无法使计时器无效

[英]Unable to invalidate timer

我试图在我的应用程序中使用计时器,在该应用程序中我想在viewWillAppear上启动计时器,并希望在viewWillDisappear方法中停止计时器。 我做了以下编码:
在.h中:@属性(非原子的,强的)NSTimer * timer;

-(void)viewWillAppear:(BOOL)animated{
   [super viewWillAppear:FALSE];
   if(!_timer){
     _timer = [NSTimer scheduledTimerWithTimeInterval: 5.0
                                              target: self
                                            selector:@selector(reloadInboxMessages)
                                            userInfo: nil repeats:YES];
  }
}

-(void)reloadInboxMessages {
  NSLog(@"reloadInboxMessages");
  [tblvwMessage reloadData];
 }

-(void)viewWillDisappear:(BOOL)animated {
   [super viewWillDisappear:FALSE];

   NSLog(@"viewWillDisappear");
   if([_timer isValid]){
       [_timer invalidate];
       _timer = nil;
   }
}

我认为这将是简单的任务要做,但我不知道为什么它不工作。 有什么问题

尝试self.timer = [NSTimercheduledTimerWithTimeInterval ...

有三种创建计时器的方法:

使用ScheduledTimerWithTimeInterval:invocation:repeats:或ScheduledTimerWithTimeInterval:target:selector:userInfo:repeats:类方法来创建计时器,并将其安排在默认模式下的当前运行循环中。

使用timerWithTimeInterval:调用:重复:或timerWithTimeInterval:目标:选择器:USERINFO:重复:类方法没有调度它在运行循环来创建计时器对象。 (创建计时器后,必须通过调用相应的NSRunLoop对象的addTimer:forMode:方法将计时器手动添加到运行循环中。)

分配计时器并使用initWithFireDate:interval:target:selector:userInfo:repeats:方法对其进行初始化。 (创建计时器后,必须通过调用相应的NSRunLoop对象的addTimer:forMode:方法将计时器手动添加到运行循环中。)

编辑:

您正在使用的方法已将其从以下方法添加到mainLoop中-使用第二种方法创建计时器并保留手动添加。

您必须在其上安装了定时器线程发送无效消息。 如果从另一个线程发送此消息,则与计时器关联的输入源可能不会从其运行循环中删除,这可能会阻止线程正常退出。

编辑:

无效即在回调传递的计时器,但不会viewWillDisappear方法中出现:。 因此,它并不完全适用于这样的场景:

  • (空隙)的OnTimer:(的NSTimer *)pTimer {[pTimer无效]; }

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM