2014-02-09 30 views
1

我有一個可以預約的iPad應用程序。如果用戶恰好與現有約會重疊,我需要通過UIAlertView讓他們知道。問題當然是,直到'Save'方法完成它的處理之後才顯示UIAlertView。在單獨的線程中顯示UIAlertView會在主線程中停止處理嗎?

我正在考慮使用單獨的線程(稱爲'B')來顯示警報,並將點擊返回到主線程的按鈕(稱爲'A')。我這樣做的方式是讓主線程('A')調用另一個方法,它會創建線程('B'),在新線程('B')上顯示警報並返回主線程'A')在用戶點擊了警報上的一個按鈕之後,返回一些指示哪個按鈕被點擊的值。

我一直希望,因爲我把線程創建放在一個單獨的方法中,調用方法會等待它返回,然後繼續在主線程('A')中處理它。

這可行嗎?

UPDATE

我只是嘗試這樣做,並沒有工作(警報被顯示方式的處理完成後,主線程繼續處理 - 不是我想要的東西!):

if(overlapFlag == [NSNumber numberWithInt:1]) { // there IS an overlap 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //Here your non-main thread. 

     NSLog (@"Hi, I'm new thread"); 

     UIAlertView *testView = [UIAlertView alertViewWithTitle:@"Warning!" message:@"This appointment overlaps an existing appointment. Tap Continue to save it or Cancel to create a new appointment."]; 
     [testView addButtonWithTitle:@"Continue" handler:^{ NSLog(@"Yay!"); }]; 
     [testView addButtonWithTitle:@"Cancel" handler:^{ [self reloadAppointmentList]; }]; 
     [testView show]; 

     dispatch_async(dispatch_get_main_queue(), ^{ //Here you returns to main thread. 

      NSLog (@"Hi, I'm main thread"); 
     }); 

    }); 

} 
+1

嘗試在SO上搜索'performSelectorOnMainThread' – Krumelur

+0

NSInvocation?我在* performSelectorOnMainThread *(我從來沒有使用它)上找不到任何* docs * – SpokaneDude

回答

2

這是可能的。

但是在後臺線程中使用UI並不是很好的做法。爲什麼不在啓動'Save'方法之前顯示UIAlertView,並在另一個線程中調用'Save'方法?例如,這將是一個更好的解決方案:

- (void) someSaveMethod{ 
    [self showAlertView]; 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE _PRIORITY_DEFAULT, 0), ^(){ 
     // call you save method 
     // after end save method call: 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [self hideAllertView]; 
     }); 
    }); 
} 
+0

*我之前沒有這些信息*我調用Save方法...它處於處理我找到了關於重疊的Save方法*中的data *。 – SpokaneDude

+1

好的,但你不應該停止主線程。正如我所看到的,只有在獲得一些數據後才能調用「保存」方法?在一種方法中,您將獲得數據,爲什麼不用這種方法調用showAlertView? – Aliaksandr

+0

我想我必須這樣做......謝謝你的幫助,我很感激它......:D – SpokaneDude

1

不需要使用單獨的線程。在查找重疊和保存過程的其餘部分之前,將保存過程分解爲所有可以處理的內容。

- (void)saveBegin 
{ 
    // start save process 
    // ... 
    // now check for overlap 
    if(overlapFlag == @1) 
    { // there IS an overlap 

     NSString *message = @"alert message goes here"; 
     UIAlertView *testView = [UIAlertView alertViewWithTitle:@"Warning!" 
                 message:message]; 

     [testView addButtonWithTitle:@"Continue" 
          handler:^{ [self saveComplete]; }]; 

     [testView addButtonWithTitle:@"Cancel" 
          handler:^{ [self reloadAppointmentList]; }]; 
     [testView show]; 

    } 
    else 
    { 
     [self saveComplete]; 
    } 

} 

- (void)saveComplete 
{ 
    // complete save process 
    // .. 
}