我有一个 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/