NSRunLoop cancelPerformSelectorsWithTarget不起作用

Nic*_*ick 0 nsrunloop ios

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

#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
Run Code Online (Sandbox Code Playgroud)

我希望函数被调用大约0次,如果CPU有一个缓慢的一天,可能是1.

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

非常感谢,尼克

Dav*_*har 5

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

例如,

[NSObject cancelPreviousPerformRequestsWithTarget:self];
Run Code Online (Sandbox Code Playgroud)

有关多点触控事件的" 事件处理指南 "的"处理点按手势"部分中有一个示例