2013-03-22 45 views
1

我有一個視圖控制器,它只顯示計算過程中的進度。我把方法調用只有在視圖出現後才自動開始計算

in viewDidLoad但問題是視圖只出現一次計算完成!

我可以在視圖出現在屏幕上後自動啓動計算嗎?

+0

線程計算 – rooster117 2013-03-22 18:35:30

回答

5

您可以使用GCD。這裏是Raywenderlich tutorial

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ 
     //Calculations 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      //Update UI must be here 
     }); 
    }); 
} 
+0

好的答案... – Mrunal 2013-03-22 18:42:39

+0

完美的作品! – Alex 2013-03-22 18:46:18

+1

不要忘記調用超類的實現。 – 2013-03-23 08:17:46

2

viewDidLoad:視圖加載時觸發。這與顯示視圖時不同。

請嘗試開始- (void)viewDidAppear:(BOOL)animated回調方法中的計算,而不是UIViewController


如果這些計算需要一段時間,考慮在後臺線程上運行它們。這將防止UI在計算運行時被鎖定。這不僅可以讓視圖顯示,而且可以在用戶等待時與其交互。

[self performSelectorInBackground:@selector(doCalc) 
         withObject:nil]; 

從這doCalc方法,你會回調,結果主線程。

[self performSelectorOnMainThread:@selector(didCalcValue:) 
         withObject:result 
        waitUntilDone:NO]; 
2

正如其他人正確地指出,viewDidAppear咱們你知道什麼時候該觀點已經出現在屏幕上。 *另外,當您使用這些事件方法時,請不要忘記撥打super

實施例:

// Tells the view controller that its view was added to the view hierarchy. 

- (void)viewDidAppear:(BOOL)animated 
{ 
    // makes sure it's also called on the superclass 
    // because your superclass may have it's own code 
    // needing to be called here 
    [super viewDidAppear:animated]; 

    // do your calculations here 

} 

常用的UIViewController事件:

– (void)viewDidLoad 

調用在存儲器當你的視圖首次加載。

– (void)viewDidAppear: 

在您的視圖出現在屏幕上後調用。

– (void)viewWillDisappear: 

調用之前您的視圖將從屏幕上消失。

請參閱關於UIViewController Class Reference page的完整列表。

相關問題