我想每500毫秒执行一段代码,总共10秒钟。我的代码工作执行每半秒钟与此代码iOS - 执行一段代码10秒
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(getLevel:) userInfo:nil repeats: YES];
,但我似乎无法弄清楚如何停止10秒后执行。 “重复”论证似乎没有考虑到特定的时间。 有人能指点我应该去哪里的方向吗?
感谢 布赖恩
我想每500毫秒执行一段代码,总共10秒钟。我的代码工作执行每半秒钟与此代码iOS - 执行一段代码10秒
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(getLevel:) userInfo:nil repeats: YES];
,但我似乎无法弄清楚如何停止10秒后执行。 “重复”论证似乎没有考虑到特定的时间。 有人能指点我应该去哪里的方向吗?
感谢 布赖恩
您需要在信息的NSTimer是invalidate
scheduledTimerWithTimeInterval:目标:选择:用户信息:重复:给你。例如,分配NSTimer该方法返回给您的属性或iVar类,并在10秒钟后调用invalidate
。
例子:
.H:
@interface myClass{
NSTimer *myT;
}
[...]
.M:
[...]
{
myT = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(getLevel:) userInfo:nil repeats: YES];
[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(stop) userInfo:nil repeats:NO];
}
-(void)stop{
[myT invalidate];
}
[...]
您可以通过实施某种finish
标志避免再次NSTimer
,如果你想和追踪有多少次你发送了getLevel
方法,因为它每隔0.5秒就会有20次。
但我宁可2个NSTimer
对象,因为你知道这是10秒不管其他计时器,它可能会决定更改,向上或向下它的频率......
完美。非常感谢。 – 2012-07-13 15:27:07
做的最好的事情是使财产对你的班级。
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) int ticks;
然后在getLevel选择称之为:
if (ticks >= 20) [self.timer invalidate];
// 20 is 10 seconds * 500 milliseconds
ticks++;
在10秒内只有20个500ms,而不是5000,if语句应该是if(ticks == 20)not> 20。 – 2012-07-13 15:13:37
谢谢你的修复。 :) – 2012-07-13 16:06:47
您可以设置其他定时器使用无效停止它。只要在伊娃或财产保留这个计时器的参考。
检查此answer欲知更多信息。
你可以去的另一种方法是定义一个选择器,例如-(void)stopTimer{}
其中你使计时器无效。然后,当你在第一时间创建计时器执行下列操作之一:
[self performSelector:@selector(stopTimer) withObject:nil afterDelay:10.0];
会[这里](http://stackoverflow.com/a/9258071/264775)回答适用? – thegrinner 2012-07-13 14:46:42