objective-c - iOS:为什么定时器(和performSelector)会立即触发选择的方法?

标签 objective-c ios

我试过两者都用:

[NSTimer scheduledTimerWithTimeInterval:2.0
                                     target:self
                                   selector:@selector(enableGestures)
                                   userInfo:nil
                                    repeats:NO];

[self performSelector:@selector(enableGestures) withObject:nil afterDelay:2.0];

触发 enableGestures 方法,但是在两个版本中它被触发了两次! (第一次是在计时器启动时,第二次是在 2 秒后)。第二个片段也一样。为什么?

谢谢

最佳答案

scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: 消息的选择器应具有以下签名:

- (void)enableGestures:(NSTimer*)theTimer

我写了一些测试代码,没有正确的选择器签名,有时会立即调用选择器,然后在计时器结束时再次调用。当我将其更改为正确的签名时,选择器在适当的延迟后首先被调用。我从来没有在签名格式正确的情况下遇到过这个问题,大约一半的时间在签名不正确的情况下遇到过这个问题。

我试过第二个版本,每次都能正常工作。

如果这两个版本的计时代码都一致发生,则代码中的其他地方正在发送 enableGestures 消息。

关于objective-c - iOS:为什么定时器(和performSelector)会立即触发选择的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6342898/

相关文章:

ios - 有没有办法实现dispatch_cancel()?

iphone - 我如何在 iPad 中使用 class_getProperty?(不是模拟器)

iphone - 图像稳定库 Objective-C/C/C++?

iphone - 文本字段方式中的键盘如何向上移动 View

ios - UIButton:如何使用 imageEdgeInsets 和 titleEdgeInsets 使图像和文本居中?

iphone - 在格式化价格时获取 NSNumberFormatter 以拼出货币

ios - 如何使用 NSUserDefaults 保存和检索数据

ios - 向字体添加自定义符号/图标

ios - Kontakt 信标和 iOS : didStartMonitoringForRegion not working as expected

iphone - 应用程序在dispatch_release信号灯上崩溃了吗?