NSRunLoop cancelPerformSelectorsWithTarget不起作用

时间:2010-09-30 12:16:02

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

非常感谢,很多, 尼克

2 个答案:

答案 0 :(得分:5)

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

例如,

[NSObject cancelPreviousPerformRequestsWithTarget:self];

Event Handling Guide for multitouch events

的“处理点击手势”部分中有一个示例

答案 1 :(得分:1)

你想要这个:

[UIApplication cancelPreviousPerformRequestsWithTarget:self];