异步函数执行?

jol*_*ger 7 iphone objective-c ios

在我的iOS应用程序中,我执行以下操作.

viewDidAppear(){

   // Load a spinner in a view on the top
   [DSBezelActivityView newActivityViewForView:self.view]; 
   // Execute code that require 3 seconds
   ...
   // Stop the spinner
   [DSBezelActivityView removeViewAnimated:YES];
}
Run Code Online (Sandbox Code Playgroud)

问题是spinner没有出现,因为cpu正在努力工作(类似的东西).这就像开始和停止之间的代码优先于视图的渲染.

我很想找到一种方法来有效地显示微调器的开始,而不使用计时器来延迟代码执行.

谢谢

Jan*_*ano 22

如果你有一个像这样的方法

-(void) showSpinner:(UIView*)view {
    dispatch_async(dispatch_get_main_queue(), ^{
        [DSBezelActivityView newActivityViewForView:view];
    });
}
Run Code Online (Sandbox Code Playgroud)

有几种方法可以从不同的线程调用它.从以下选择一个:

[NSThread detachNewThreadSelector:@selector(showSpinner:) toTarget:self withObject:self.view];
// or 
[self performSelectorInBackground:@selector(showSpinner:) withObject:self.view];
// or 
NSInvocationOperation *invOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(showSpinner:) object:self.view];
NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
[opQueue addOperation:invOperation];
// or 
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self showSpinner:self.view];
});
Run Code Online (Sandbox Code Playgroud)

Alt +单击以获取详细信息.