【问题标题】:iOS NSTimer not working? [duplicate]iOS NSTimer 不工作? [复制]
【发布时间】:2012-08-13 09:29:13
【问题描述】:

这是我的确切代码,但它似乎不起作用。你能告诉我我做错了什么吗?请注意,refreshTimer 已在私有接口中声明。

-(void)viewDidLoad {
refreshTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerTest)      userInfo:nil repeats:YES];

}
-(void)timerTest {
NSLog(@"Timer Worked");
}

【问题讨论】:

  • 设置重复:不,它对我有用..

标签: ios ios5 methods nstimer


【解决方案1】:

试试scheduledTimerWithTimeInterval

NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];

引用:NSTimer timerWithTimeInterval: not working

scheduledTimerWithTimeInterval:invocation:repeats: 和scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: 创建自动添加到NSRunLoop 的计时器,这意味着您不必自己添加它们。将它们添加到 NSRunLoop 是导致它们被触发的原因。

【讨论】:

    【解决方案2】:

    有两种选择。

    如果使用timerWithTimeInterval

    使用喜欢它的追随者。

    refreshTimer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:refreshTimer forMode:NSRunLoopCommonModes];
    

    模式也是两个选项。 NSDefaultRunLoopModeNSRunLoopCommonModes

    更多信息。请参阅此文档:RunLoopManagement


    如果使用scheduledTimerWithTimeInterval

    使用喜欢它的追随者。

    refreshTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
    

    计划的计时器会自动添加到运行循环中。

    更多信息。请参阅此文档:Timer Programming Topics

    总结

    你必须记住的“timerWithTimeInterval” 将计时器添加到您要添加的运行循环中。

    scheduledTimerWithTimeInterval”默认自动创建一个运行在 当前循环。

    【讨论】:

      猜你喜欢
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 2017-12-15
      相关资源
      最近更新 更多