2009-07-14 44 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];