2017-03-17 143 views
0

我來這裏是正確的需要螺紋的問題,但我似乎不能正確地優化它。正確的線程處理

這裏是我的方法:

-(void) method1 
{ 
    // -1 to an NSInteger 
    nsint1--; 

    [self showActiviyIndicator:YES]; //act as loading screen 

    [alloc database etc stuffs and retrieving of data here] 

    //for loop here to check with database, and grey out button depending on database values 
    for (int i = 1; i<12; i ++) 
    { 
    //get values from database and store into variables, then grey out the button if variables are 0. 
    } 

    int Val1 = [get from database] 

    if Val1 = 0 
    [button setTitleColor:[UIColor Grey]]; 

    someLabel.text = [NSString stringWithFormat:@"%ld", (long)nsint1]; 

    //here's where the problem lies 
    [self refreshTableSessionList:xx]; 

    [self showActiviyIndicator:NO] 
} 

內[自refreshTableSessionList:XX],有一個

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) 

從服務器數據庫獲取數據,然後

dispatch_async(dispatch_get_main_queue(), 

填充並重新加載tableViewCell。

但是這樣會有當我把一個

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) 

[alloc database etc stuffs and retrieving of data here] 前變灰的按鈕時把dispatch_async(dispatch_get_main_queue(), 衝突,但是這是一個循環中,我不認爲這是正確的辦法。

什麼是克服這種解決辦法嗎?

+0

使用塊從服務器數據庫獲取數據。 – Kampai

+0

你的循環在哪裏? – 2017-03-17 07:37:17

+0

的可能的複製[iPhone - 大中央調度主線程(http://stackoverflow.com/questions/7905192/iphone-grand-central-dispatch-main-thread) – 2017-03-17 07:39:37

回答

1

我瞭解你不等待的後臺數據庫的東西終點。

你看了關於多線程?例如,Ray's article

在一個簡單的方法,你可以調用dispatch_async的dispatch_async內dipatch_async塊內等

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    // do some database stuff 
    dispatch_async(dispatch_get_main_queue(), ^{ 
    // do some UI stuff 
    }); 
}); 

所以,你應該在主線程和全局隊列之間進行切換。此外,您可以使用代表,通知甚至反應性來達到此目的。

+0

這很好,你想幫忙,但是請避免回答以前已經回答過100次的問題。如果您覺得合適,請將其標記爲重複。 – 2017-03-17 07:40:12

+0

感謝您的鏈接,現在看看它,以及雷的塊教程。謝謝。 – JackyW