2011-05-29 60 views
2

我已經成立了一個標籤佈局我的iPhone應用程序的計算/處理數據,我想執行一些相當激烈計算(可能需要幾秒鐘才能獲得結果),當用戶選擇一個的選項卡。使用UIAlertView中等待

最初,它會出現在執行數字運算時iphone會掛在原始選項卡上。

我試着添加一個UIAlertView作爲一些眼睛糖果,但我漸漸灰暗了幾秒鐘,然後計算完成後,快速出現/視圖消失。我想看到的是UIAlertView中出現/動畫當用戶觸摸選項卡,然後消失,一旦計算完成

- (void)viewDidAppear:(BOOL)animated 
{  


    UIAlertView *baseAlert = [[[UIAlertView alloc] initWithTitle:@"Calculating" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil]autorelease]; 
    [baseAlert show]; 
    UIActivityIndicatorView *aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; 
    aiv.center = CGPointMake(baseAlert.bounds.size.width /2.0f, baseAlert.bounds.size.height - 40.0f); 
    [aiv startAnimating]; 
    [baseAlert addSubview:aiv]; 
    [aiv release]; 


/*** calculation and display routines***/ 


    [baseAlert dismissWithClickedButtonIndex:0 animated:YES]; 
} 

我已經看到this post,但我似乎無法弄清楚如何將其應用於我的案例。

回答

6

解決此問題的最簡單方法是使用塊;首先進度計算使用第一塊單獨的線程,完成後通過塊出動主線程關閉提醒觀點:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{ 

// Do calculations 


dispatch_async(dispatch_get_main_queue(),^
         { 
          [baseAlert dismissWithClickedButtonIndex:0 animated:YES]; 
         }); 
}); 
+0

那是光榮的!謝謝 – Rasman 2011-05-29 21:43:20

0

可能發生的情況是,您正在執行的「密集計算」正在與您調用UIAlertView的位置相同的線程中運行。設置一個委託UIAlertView中就設置了一個單獨的線程,這樣你就不需要擔心競爭,以及是否會UIAlertView中計算前露面。

另外,使用UIAlertView中是一個相當重手的方式 - 也許當你緊縮一些數字,你可以使用一些其他的界面元素來顯示進度,而不是渲染應用無用的?

4

您需要了解事件循環的作品。當你調用[baseAlert show],警報視圖添加到視圖層次,但實際上並沒有吸引到屏幕上,直到當前的代碼塊結束和控制返回到事件循環。通過詢問警報視圖來顯示後立即做你的計算,你是防止警報從不斷出現。

這有點像寫一封信,告訴你打算粉刷你家的人,花一個星期畫你的房子,然後寫另一封信,說你已經做到了,並THEN採取字母和在拖放郵箱同時交付。

如果你有一個昂貴的計算,在iOS 4和更高版本中處理它的最簡單方法是將一個代碼塊放入一個調度隊列中,這樣工作將在後臺線程中完成,而主線程可以仍然更新屏幕並響應手指點擊。

[baseAlert show]; 
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{ 
    // we're on a secondary thread, do expensive computation here 
    // when we're done, we schedule another block to run on the main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     // this code is back on the main thread, where it's safe to mess with the GUI 
     [baseAlert dismissWithClickedButtonIndex:0 animated:YES]; 
    }); 
}); 
+0

欣賞解釋 – Rasman 2011-05-29 21:43:15