2010-05-04 77 views
0

我試圖做這樣的事情:視圖疊加添加到iPhone應用程序

- (void)sectionChanged:(id)sender { 
    [self.view addSubview:loadingView]; 
    // Something slow 
    [loadingView removeFromSuperview]; 
} 

其中loadingView是一個UIActivityIndi​​catorView半透明視圖。但是,似乎添加的子視圖更改直到此方法結束纔會生效,因此在視圖變爲可見之前將其刪除。如果我刪除removeFromSuperview語句,那麼在緩慢的處理完成之後視圖會正常顯示,並且永遠不會被刪除。有什麼辦法可以解決這個問題嗎?

回答

4

運行在後臺線程你緩慢的過程:

- (void)startBackgroundTask { 

    [self.view addSubview:loadingView]; 
    [NSThread detachNewThreadSelector:@selector(backgroundTask) toTarget:self withObject:nil]; 

} 

- (void)backgroundTask { 

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    // do the background task 

    [self performSelectorOnMainThread:@selector(backgroundTaskDone) withObject:nil waitUntilDone:NO]; 
    [pool release]; 

} 

- (void)backgroundTaskDone { 

    [loadingView removeFromSuperview]; 
} 
+0

非常好,謝謝。 dannywartnaby的答案几乎完全相同,但我讓你記住一個自動釋放池。 – 2010-05-04 21:56:34

1

兩個潛在的問題映入腦海,圍繞你是如何實現「在這裏做一些慢」的代碼都居中。

首先,如果它鎖定了主線程,那麼應用程序的UI可能不會被重繪以及時顯示視圖,即添加子視圖,緊密循環/密集處理捆綁主線程,然後立即該視圖被刪除。其次,如果'異步緩慢'是異步完成的,則視圖在緩慢處理運行時被刪除。

肯定

一個東西,你的要求如下:

  1. 添加一個子視圖來顯示某種「裝載」鑑於
  2. 調用運行速度慢一塊的功能
  3. 一旦慢跑功能完成,刪除'加載'子視圖。

- (void)beginProcessing { 
    [self.view addSubview:loadingView]; 
    [NSThread detachNewThreadSelector:@selector(process) toTarget:self withObject:nil]; 
} 

- (void)process { 

    // Do all your processing here. 

    [self performSelectorOnMainThread:@selector(processingComplete) withObject:nil waitUntilDone:NO]; 
} 

- (void)processingComplete { 
    [loadingView removeFromSuperview]; 
} 

你也可以實現與NSOperations類似的東西。

相關問題