我有一个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];
您应该取一个计数器,每次调用方法时递增,计数5,然后使用以下代码使计时器无效。
[timer invalidate];
要从当前循环中销毁计时器,您应该调用[timer invalidate];
要确定五次出现,需要维护一个变量并每次递增其计数。如果它等于5,则调用invalide方法。
首先,您需要声明int
和NSTimer *timer
,这样我们就可以停止它:
@interface AppDelegate : UIViewController {
int myInt;
NSTimer *timer;
}
要启动NSTimer
,您只需要更改一点代码:
timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(yourMethod) userInfo:nil repeats:YES];
在你的void函数中,你可以进行验证,以检查代码是否在5次迭代后运行:
- (void)myVoid{
NSLog(@"Call Me");
if (myInt == 5) {
[timer invalidate];
timer = nil;
}
myInt++;
}