2010-09-30 2 views
0

J'ai le code suivant et je n'obtiens pas les résultats attendus.NSRunLoop cancelPerformSelectorsWithTarget ne fonctionne pas

#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 

Je m'attendais à ce que la fonction soit appelée environ 0 fois, peut-être 1 si la CPU a un jour lent.

La fonction sera exécutée 10 fois! .? :(toujours ce que je fais mal, et comment pourrais-je obtenir les résultats que je pensais

Merci à l'avance, beaucoup, Nick

Répondre

5

Vous voulez annuler la demande en utilisant la méthode de classe NSObject + cancelPreviousPerformRequestsWithTarget:

Par exemple,

[NSObject cancelPreviousPerformRequestsWithTarget:self]; 

Il y a un exemple dans la « manipulation des gestes du robinet » section du Event Handling Guide for multitouch events

1

Vous voulez ceci:

[UIApplication cancelPreviousPerformRequestsWithTarget:self]; 
+0

Cela fonctionne aussi, parce que 'UIApplication' hérite de la méthode de' NSObject' –