我們正試圖獲得一個後臺任務,用於在工作室屏幕中包含活動指示器。根據我們的理解,這需要創建一個後臺線程來運行它。我也明白,在後臺線程上不能執行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;
}
到目前爲止,工作得很好,只是我們還沒有辦法知道當後臺任務完成時。只有完成後,我們才能處理後臺任務的結果。現在,它不起作用,因爲沒有與這兩者同步。怎麼解決?
另一件事,注意到一個微調現在顯示在狀態欄中。這是一件好事,但在後臺任務完成後似乎沒有消失。該怎麼辦?
在此先感謝。
謝謝。我在這裏使用此代碼嘗試了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
當您收到KVO通知時,您在做什麼?你在那裏做任何UIKit嗎? – Tommy 2010-11-17 21:41:27