代码之家  ›  专栏  ›  技术社区  ›  Nick

NSRunLoop cancelperformselector with target不工作

  •  0
  • Nick  · 技术社区  · 15 年前

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

    #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 回复  |  直到 15 年前
        1
  •  5
  •   David Gelhar    15 年前

    您想使用 NSObject

    例如,

    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    

    在本教程的“处理点击手势”部分有一个例子 Event Handling Guide for multitouch events

        2
  •  1
  •   Jim os x nerd    15 年前

    你想要这个:

    [UIApplication cancelPreviousPerformRequestsWithTarget:self];