ios - NSRunLoop cancelPerformSelectorsWithTarget 不工作

标签 ios nsrunloop

我有以下代码,但没有得到预期的结果。

#import "CancelPerformSelectorTestAppDelegate.h"
@implementation CancelPerformSelectorTestAppDelegate
@synthesize window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    [window makeKeyAndVisible];
    for(unsigned int i = 0; i < 10; i++){
        NSTimeInterval waitThisLong = i;
        [self performSelector:@selector(foo) withObject:nil afterDelay: waitThisLong];
    }

    [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: self];

    return YES;
}

- (void) foo {
    static unsigned int timesCalled = 0;
    ++timesCalled;
    NSLog(@"%s: I am called for the %d-st/nd/th time", __func__, timesCalled);
}

- (void)applicationWillResignActive:(UIApplication *)application {}
- (void)applicationDidBecomeActive:(UIApplication *)application {}
- (void)applicationWillTerminate:(UIApplication *)application {}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {}
- (void)dealloc {
    [window release];
    [super dealloc];
}

@end

我预计该函数将被调用大约 0 次,如果 CPU 运行缓慢,则可能调用 1 次。

该函数将执行 10 次! :( 总是。我做错了什么,我怎样才能达到预期的结果?

非常感谢, 尼克

最佳答案

您想使用 NSObject 取消请求类方法 +cancelPreviousPerformRequestsWithTarget:

例如,

[NSObject cancelPreviousPerformRequestsWithTarget:self];

Event Handling Guide for multitouch events 的“处理点击手势”部分有一个示例

关于ios - NSRunLoop cancelPerformSelectorsWithTarget 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3830383/

相关文章:

带工具栏的操作表中的 iphone uidatepicker?

ios - 如何在沙盒模式 iOS 中测试应用内购买?

ios - 如何防止导航栏随着 MSMessagesViewController -> UIContainerView -> UINavigationController -> UITableViewController 消失?

ios - 如何重新加载具有不同行数的 UITableView 部分?

ios - Restkit 0.2 加载两个具有相同实体和不同谓词的不同表时遇到问题

ios - 蓝牙通信 NSStream 是否应该需要一个单独的线程?

objective-c - 关于 NSRunLoop,需要澄清

ios - 为什么此线程不执行最后一行代码

objective-c - NSRunLoop- 需要澄清

ios - 是否应该始终将 NSTimer 添加到运行循环中以执行