iphone - 定时器不重复

标签 iphone ios

我的计时器不重复请帮忙

这是代码

timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(doAnimation:) userInfo:nil repeats:YES];
[timer fire];

方法

-(void)doAnimation:(id)Sender
{
}

最佳答案

[timer fire] 手动触发计时器 仅一次 并且实际上并未“启动”计时器。来自docs :

You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.

您需要add the timer在开始触发和重复之前的运行循环中:

You must add the new timer to a run loop, using addTimer:forMode:. Then, after seconds seconds have elapsed, the timer fires, sending the message aSelector to target. (If the timer is configured to repeat, there is no need to subsequently re-add the timer to the run loop.)

更简单的方法是执行以下操作:

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doAnimation:) userInfo:nil repeats:YES];

和:

-(void)doAnimation:(NSTimer*)timer
{
}

automatically schedules计时器并将其添加到运行循环中。以防万一你没有这样做,因为你已经将目标设置为 self 你必须确保方法 doAnimation 是在同一个类中定义的。

NSTimer Class Reference

关于iphone - 定时器不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7990122/

相关文章:

iphone - 核心数据和特殊字符(UTF-8)

ios - 使用 Storyboard将数据从注释传递到详细 View iOS

iphone - 从 WebDriver 传递键盘事件无法正常运行 iOS 模拟器/设备

iphone - iPhone 上嵌入的 Youtube 视频问题

objective-c - IOS - 使用 #import 类的正确方法

ios - 3D触摸: unexpectedly found nil while unwrapping an Optional value

ios - Swift - 在 plist 中的数组中搜索字典

iphone - 网站在 iPhone 上显示很小

ios - Kinvey iOS 查询所有用户

objective-c - 如何在Objective C(NSRegularExpression)中编写正则表达式?