我有以下代码,但没有得到预期的结果。
#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次!:( 总是。我做错了什么,我怎么能达到我预期的结果?
非常感谢,尼克