2010-11-16 89 views
0

我們正試圖獲得一個後臺任務,用於在工作室屏幕中包含活動指示器。根據我們的理解,這需要創建一個後臺線程來運行它。我也明白,在後臺線程上不能執行GUI更新。iPhone SDK:如何知道後臺任務何時完成?

鑑於此,這裏是需要發生的一般模式。

a。)預驗證字段。確保用戶沒有輸入任何無效數據 b。)設置後臺任務。從後臺任務 C)處理結果

這就是它看起來像在到目前爲止的代碼:

-(IBAction)launchtask:(id)sender 
{ 
    //validate fields 
    [self validateFields]; 

    /* Operation Queue init (autorelease) */ 
    NSOperationQueue *queue = [NSOperationQueue new]; 

    /* Create our NSInvocationOperation to call loadDataWithOperation, passing in nil */ 
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self 
                      selector:@selector(backgroundTask) 
                       object:nil]; 

    /* Add the operation to the queue */ 
    [queue addOperation:operation]; 
    [operation release]; 


    //TO DO: Add any post processing code here, BUT how do we know when it is done??? 
    ConfirmationViewController *otherVC; 

    //show confirm 
    //if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    //{ 
    // otherVC = [[ConfirmationViewController alloc] initWithNibName:@"ConfirmationViewPad" bundle:nil]; 
    //} 
    //else 
    { 
     otherVC = [[ConfirmationViewController alloc] initWithNibName:@"ConfirmationView" bundle:nil]; 
    } 

    //TO DO: Let's put this in a struct 
    otherVC.strConfirmation = strResponse; 
    otherVC.strCardType = strCardType; 
    otherVC.strCardNumber = txtCardNumber.text; 
    otherVC.strExpires = txtExpires.text; 
    otherVC.strCustomerEmail = txtEmail.text; 

    [self.navigationController pushViewController:otherVC animated:YES]; 
    [otherVC release]; 
    otherVC = nil; 


} 

到目前爲止,工作得很好,只是我們還沒有辦法知道當後臺任務完成時。只有完成後,我們才能處理後臺任務的結果。現在,它不起作用,因爲沒有與這兩者同步。怎麼解決?

另一件事,注意到一個微調現在顯示在狀態欄中。這是一件好事,但在後臺任務完成後似乎沒有消失。該怎麼辦?

在此先感謝。

回答

0

您的選項是,簡單:

  • 鍵值觀察「operationCount」屬性上NSOperationQueue並等待它達到0(或等同的「操作」屬性,並檢查計數)
  • 讓你的操作發出一個小通知,說明它們已經完成(可能在主線程上執行了performSelectorOnMainThread:...),並等待收到正確數量的通知。

[編輯:我看到你已經具體詢問了舊的SDK 3.0。在這種情況下,觀察操作並檢查計數,因爲operationCount屬性postdates SDK 3.0]

在一般情況下,沒有自動啓動和停止微調控制器的系統。你必須自己談談。然而,對於微調者來說,一件簡單的事情是,即使主線程被阻塞,它仍然繼續旋轉,所以如果你是爲了這個目的而跳線,那麼你實際上並不需要。

我相信,狀態欄中會出現一個微調以顯示數據提取。如果它繼續旋轉,那麼您仍然有URL請求正在進行,無論您是否真的在等待結果。

+0

謝謝。我在這裏使用此代碼嘗試了KVO方法。 http://zh.efreedom.com/Question/1-1049001/Get-Notification-NSOperationQueue-Finishes-Tasks我得到的通知說,操作完成,但它錯了與此。布爾_WebTryThreadLock(布爾),0x885ac40:試圖從主線程或Web線程以外的線程獲取Web鎖。這可能是從輔助線程調用UIKit的結果。現在崩潰...如果它在後臺線程中有任何區別,我正在進行同步ASIHTTPRequest調用。 – butchcowboy 2010-11-16 17:22:22

+0

當您收到KVO通知時,您在做什麼?你在那裏做任何UIKit嗎? – Tommy 2010-11-17 21:41:27

相關問題