NSRunLoop cancelPerformSelectorsWithTarget's not working

烈酒焚心 提交于 2019-12-13 21:11:39

问题


I have this following code and I am not getting the results I expected.

#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

I expected the function to be called about 0 times, perhaps 1 if the CPU is having a slow day.

The function will execute 10 times! :( Always. What am I doing wrong, and how could I achieve the results I expected?

Thanks in advance, a lot, Nick


回答1:


You want to cancel the request using the NSObject class method +cancelPreviousPerformRequestsWithTarget:

For example,

[NSObject cancelPreviousPerformRequestsWithTarget:self];

There's an example in the "handling tap gestures" section of the Event Handling Guide for multitouch events




回答2:


You want this:

[UIApplication cancelPreviousPerformRequestsWithTarget:self];


来源:https://stackoverflow.com/questions/3830383/nsrunloop-cancelperformselectorswithtargets-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!