iPhone SDK:如何知道后台任务何时完成?

问题描述:

我们正试图获得一个后台任务,用于在工作室屏幕中包含活动指示器。根据我们的理解,这需要创建一个后台线程来运行它。我也明白,在后台线程上不能执行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; 


} 

到目前为止,工作得很好,只是我们还没有办法知道当后台任务完成时。只有完成后,我们才能处理后台任务的结果。现在,它不起作用,因为没有与这两者同步。怎么解决?

另一件事,注意到一个微调现在显示在状态栏中。这是一件好事,但在后台任务完成后似乎没有消失。该怎么办?

在此先感谢。

您的选项是,简单:

  • 键值观察“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