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

1

あなたはこれを求めている:

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