2009-07-14 64 views
6

如果我有一个设置的延迟之后触发一个performSelector一个观点:如何杀死延迟后在iPhone上启动的选择器?

[self performSelector:@selector(generateBall) withObject:NULL afterDelay:1.5]; 

...但我removeFromSuperview选择火灾之前视图(例如,由于用户交互),那么我的应用程序崩溃。

有没有办法杀死该视图的dealloc方法中的延迟选择器?

编辑:

我都试过:

[[NSRunLoop mainRunLoop] cancelPerformSelector:theBall target:self argument:nil]; 

[[NSRunLoop currentRunLoop] cancelPerformSelector:theBall target:self argument:nil]; 

,并同时兼具工作(允许我加载新的视图),加载以前的视图结束给我一个灰色的屏幕。

我一直没能找到任何教程或约cancelPerformSelector比苹果文档等中所列示的其他信息,以及线程的文件并运行的循环似乎很令人费解(主要是因为他们没有列出工作代码示例,这将使我更容易理解并理解正在发生的事情)。

回答

15

因为我使用performSelector:afterDelay,我已经能够正确地“杀死”任何先前请求但尚未推出的功能是使用的唯一途径:

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:theBall object:nil]; 

以下代码示例显示了这是如何工作的(创建一个新的View模板XCode proj ECT所谓的“选择”,以及与此替换selectViewController.h文件):

#import "selectViewController.h" 

@implementation selectViewController 

UILabel *lblNum; 
UIButton *btnStart, *btnStop; 
int x; 

- (void) incNum { 
    x++; 
    lblNum.text = [NSString stringWithFormat:@"%i", x]; 
    [self performSelector:@selector(incNum) withObject:NULL afterDelay:1.0]; 
} 

- (void) stopCounter { 
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(incNum) object:NULL]; 
} 

- (void)viewDidLoad { 
    x = 0; 

    lblNum = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 460)]; 
    lblNum.textAlignment = UITextAlignmentCenter; 
    [self.view addSubview:lblNum]; 

    btnStart = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    btnStart.frame = CGRectMake(40, 270, 240, 30); 
    [btnStart setTitle:@"start" forState:UIControlStateNormal]; 
    [btnStart addTarget:self action:@selector(incNum) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:btnStart]; 

    btnStop = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    btnStop.frame = CGRectMake(40, 310, 240, 30); 
    [btnStop setTitle:@"stop" forState:UIControlStateNormal]; 
    [btnStop addTarget:self action:@selector(stopCounter) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:btnStop]; 

    [self performSelector:@selector(incNum) withObject:NULL afterDelay:1.0]; 
    [super viewDidLoad]; 
} 


- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
} 

- (void)viewDidUnload { 
} 

- (void)dealloc { 
    [lblNum release]; 
    [super dealloc]; 
} 

@end 
3

我发现这个伟大工程:

[NSObject cancelPreviousPerformRequestsWithTarget:self];