UIActivityIndi​​catorView未按预期加载

时间:2014-03-04 15:15:01

标签: ipad cocoa-touch uiactivityindicatorview

我正在尝试加载一个UIActivityIndicatorView然而有一些混乱,那么它应该加载。

它应该从第[activityIndicatorView startAnimating];行开始,还是到达函数的末尾。

- (void)LoadBuayView{
    activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicatorView.center = self.view.center;
    activityIndicatorView.backgroundColor = [UIColor grayColor];
    [activityIndicatorView hidesWhenStopped];
    [self.view addSubview:activityIndicatorView];
    [activityIndicatorView startAnimating];
}
- (IBAction) EditSave:(id)sender {

    [self LoadBuayView];

    for(int i =0; i<5; i++)
    {
        //Some very long takes time code
    }
}

2 个答案:

答案 0 :(得分:0)

activityIndi​​catorView将在mainThread的下一个runloop中启动动画,因此你可以认为它从函数结束开始。

您可以尝试使用以下代码来显示指标视图:

- (IBAction) EditSave:(id)sender {
    [self LoadBuayView];
    [self performSelector:@selector(doLongTimeTask) withObject:nil afterDelay:0.01];

}

- (void)doLongTimeTask{
    for(int i =0; i<5; i++)
    {
        //Some very long takes time code
    }
}

答案 1 :(得分:0)

任何耗时的进程都不应该在主队列中进行,而是应该采用Concurrency Programming Guide中讨论的异步编程模式。最重要的是,你永远不应该阻止主队列。最好的情况是,阻止主队列可能会导致用户体验不理想,最糟糕的情况是,你的应用程序可能会被iOS看门狗进程杀死。

相反,将耗时的代码分配给后台队列(调度队列或操作队列)。您可以创建自己的自定义后台队列,也可以使用GCD,您可以利用现有的后台队列之一:

- (void)loadBuyView{
    activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicatorView.center = self.view.center;
    activityIndicatorView.backgroundColor = [UIColor grayColor];
    [activityIndicatorView hidesWhenStopped];
    [self.view addSubview:activityIndicatorView];
    [activityIndicatorView startAnimating];
}

- (IBAction) didTouchUpInsideSaveButton:(id)sender {

    [self loadBuyView];

    // always do slow processes on a background queue, not the main queue

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (int i = 0; i < 5; i++)
        {
            // Some code that takes a very long time
        }

        // when done, dispatch the stopping of the activity indicator view back to the main queue;
        // all UI updates should be performed on the main queue

        dispatch_async(dispatch_get_main_queue(), ^{
            [activityIndicatorView stopAnimating];
        });
    });
}

有关上述异步编程模式的更多信息,请参阅WWDC 2012视频Asynchronous Design Patterns with Blocks, GCD, and XPC。有关各种并发编程技术的背景知识,请参阅Concurrency Programming Guide