可能重复:
如何定期调用目标 c 中的方法?
我正在制作一个应用程序,当用户触摸屏幕时,会调用以下方法:
- (void)explode:(int)x
用户只需触摸屏幕一次,但我希望该方法每 0.1 秒重复调用 100 次,然后它应该停止调用。
有没有办法在传递整数的方法上设置这样的“临时”计时器?
可能重复:
如何定期调用目标 c 中的方法?
我正在制作一个应用程序,当用户触摸屏幕时,会调用以下方法:
- (void)explode:(int)x
用户只需触摸屏幕一次,但我希望该方法每 0.1 秒重复调用 100 次,然后它应该停止调用。
有没有办法在传递整数的方法上设置这样的“临时”计时器?
You could pass a counter and the 'x' as into the timer's userInfo. Try this:
Create the timer in the method that's catching the touch event and pass a counter and the int 'x' into the userInfo:
NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithCapacity:2];
[userInfo setValue:[NSNumber numberWithInt:x] forKey:@"x"];
[userInfo setValue:[NSNumber numberWithInt:0] forKey:@"counter"];
[NSTimer timerWithTimeInterval:0.1
target:self
selector:@selector(timerMethod:)
userInfo:userInfo
repeats:YES];
Create the timer method, check the userInfo's number count, and invalidate the timer after 100 times:
- (void)timerMethod:(NSTimer *)timer
{
NSMutableDictionary *userInfo = timer.UserInfo;
int x = [[userInfo valueForKey:@"x"] intValue];
// your code here
int counter = [[userInfo valueForKey:@"counter"] intValue];
counter++;
if (counter >= 100)
{
[timer invalidate];
}
else
{
[userInfo setValue:[NSNumber numberWithInt:x] forKey:@"x"];
[userInfo setValue:[NSNumber numberWithInt:counter] forKey:@"counter"];
}
}
Please also see the Apple docs on NSTimer
: