ios - iphone 开发 : nstimer calling a function

标签 ios cocoa-touch function nstimer method-call

我有一个 void 函数,它的主体中只有 NSLog(@"Call me");

我每十秒调用一次

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(yourMethod) userInfo:nil repeats:YES];

但我希望它在 5 次迭代后停止。然而,它走向无穷大。我该怎么做?

最佳答案

1) 保留一个全局变量,从 0 递增到 5。

  int i = 0;

2) 在你的计时器函数中增加这个变量..

-(void) yourFunction:(NSTimer*)timer{
  //do your action

  i++;
  if(i == 5){
     [timer invalidate];
  }
}

3) 创建定时器时

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 
                 target:self 
                 selector:@selector(yourMethod:) // <== see the ':', indicates your function takes an argument 
                 userInfo:nil 
                 repeats:YES];

关于ios - iphone 开发 : nstimer calling a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12091161/

相关文章:

iphone - 为 iPhone 定制 UISlider

ios - 如何从 UIStoryboardSegue 动画中的目的地复制设计?

ios - 从 CocoaTouch 库调用 NSLog

objective-c - 如何制作这样的 UIBarButtonItem

php - 如何将代码包装在函数内使该代码不起作用?

ios - 我想更改 Objective C 标题中的颜色。为 ios 创建调整

ios - 身份检查器中的模块字段用于什么?

ios - Cocoa Touch 框架依赖

r - 在 R 函数中调用 "self"作为参数

matlab - 输入矩阵到ode45的函数文件