0

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

#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次!:( 总是。我做错了什么,我怎么能达到我预期的结果?

非常感谢,尼克

4

2 回答 2

5

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

例如,

[NSObject cancelPreviousPerformRequestsWithTarget:self];

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

于 2010-09-30T12:47:22.290 回答
1

你要这个:

[UIApplication cancelPreviousPerformRequestsWithTarget:self];
于 2010-09-30T12:41:09.870 回答