iPhone - NSTimer 在火灾后不重复
我正在创建并触发一个 NSTimer
:
ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(handleTimer:)
userInfo:nil
repeats:YES];
[ncTimer fire];
并且
- (void)handleTimer:(NSTimer *)chkTimer {
// do stuff
}
我正在保留我的计时器:
@property (nonatomic, retain) NSTimer *ncTimer;
出于某种原因,计时器不重复。它只会发射一次,并且不会再发射。
I am creating and firing a NSTimer
with:
ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(handleTimer:)
userInfo:nil
repeats:YES];
[ncTimer fire];
AND
- (void)handleTimer:(NSTimer *)chkTimer {
// do stuff
}
I am retaining my timer with:
@property (nonatomic, retain) NSTimer *ncTimer;
For some reason the timer is not repeating. It is firing once only and than never again.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
-fire:
方法手动触发一次。要启动并重复计时器,您必须使用[[NSRunLoop currentRunLoop] addTimer: forMode:] 将其添加到运行循环中
The
-fire:
method manually fires it once. For a timer to be started and repeat, you have to add it to a runloop using[[NSRunLoop currentRunLoop] addTimer: forMode:]
明白了,
将计时器添加到
mainRunLoop
使其正常工作Got it
Adding timer to
mainRunLoop
made it working ????????????Here you go:
Objective C:
Swift 2
Swift 3, 4, 5
您不能只分配给作为属性放入标头中的计时器。这应该有效:
另外: fire 方法会在循环外触发计时器。如果计时器不重复,则其无效。在显示“fire”的行之后,添加以下内容:
You can't just assign to the timer that you have put as a property in your header. This should work:
Also: The fire method fires the timer, out of cycle. If the timer is non repeating it is invalidated. After the line that says fire, add this:
您还可以将代码复制到该块内,这会在主线程中插入计时器的创建。
因此,代码将保留:
You can also copy your code inside this block, which inserts the creation of the Timer in the main thread.
The code will therefore remain:
我不知道为什么,但 Timer.scheduledTimer 方法不起作用,但 Timer.init 方法起作用。
I don't know why but Timer.scheduledTimer method is not working but Timer.init method worked.
分配给
ncTimer
不会启动属性retain
功能。假设声明位于成员对象内,您需要执行以下操作:
Assigning to
ncTimer
as you have will not initiate the propertiesretain
functionality.Assuming the declaration is within the member object you will need to do:
您可以在 Swift 中编写相同的内容,而无需在主循环中运行:
You could write the same thing in Swift without running in main loops by:
带闭包的 Swift 定时器:
Swift timer with closure: