NSRunLoop cancelPerformSelectorsWithTarget不工作

我有下面的代码,我没有得到我期望的结果。

#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]; 

“ 事件处理指南 ”的“处理轻敲手势”部分中有一个示例, 用于多点触控事件

你要这个:

 [UIApplication cancelPreviousPerformRequestsWithTarget:self];