0

当我点击我的按钮时,我的函数被调用

[myBtn addTarget:self action:@selector(myFunction) forControlEvents:UIControlEventTouchUpInside];

在我的函数中,将执行一组复杂的语句并花费一点时间来运行,所以我想显示 Loading (UIActivityIndi​​catorView) 如下:

-(void) addTradeAction {
    //Show Loading
    [SharedAppDelegate showLoading];

    //disable user interaction
    self.view.userInteractionEnabled = NO;

    //execute call webservice in here - may be take 10s
    //Hide Loading
    [ShareAppDelegate hideLoading];
}

当点击 myBtn(我的按钮)-> 3s 或 4s 后,[ShareAppDelegate showLoading] 被调用。

当我在其他函数上使用 [ShareAppDelegate showLoading] 时,这是不寻常的,-> 它工作得非常好,我的意思是所有语句都按顺序执行。

所有我想要的,当我点击我的按钮时,将立即调用加载。

提前谢谢

4

3 回答 3

2

在后台执行任务并在您的情况下显示活动指示器的正确方法是:

-(void)myBackGroundTask
{
    //here showing the 'loading' and blocking interaction if you want so

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //here everything you want to perform in background

        dispatch_async(dispatch_get_main_queue(), ^{ 
            //call back to main queue to update user interface
        });
    });
}

使用这种块,您可以确保您的界面不会冻结,并保持流畅的动画。

于 2013-10-29T16:10:47.777 回答
1

如果您的复杂语句没有任何 UI 动画或 UI 相关代码,那么您可以在不同的线程(除了 mainThread)中执行该部分。一旦语句完成(或在完成块中),您可以在那里删除 loadingOverlay。

于 2013-10-29T15:52:03.627 回答
0

将 myFunction 放在后台队列上运行,因为它可能会使系统挂起:

- (void)myFunction {
   dispatch_queue_t myQueue = dispatch_queue_create("myQueue", NULL);

    // execute a task on that queue asynchronously
    dispatch_async(myQueue, ^{
       // Put the current myFunction code here.
    });

}
于 2013-10-29T15:49:32.890 回答