
- (IBAction)signInBttn:(ID)sender { MBProgressHUD *hudd = [MBProgressHUD showHUDAddedTo:self.vIEw animated:YES]; hudd.mode = MBProgressHUDModeAnnularDeterminate; hudd.labelText = @"Loading"; __block float value = 0; for (int j = 0; j<2000; j++) { dispatch_async( dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAulT,0),^{ for (int i = 0; i<20000 ; i++) { } value += 0.001; dispatch_async( dispatch_get_main_queue(),^{ hudd.progress = value; }); }); } } hud完全达到100%.这仅仅是为了我的信息,我不知道如何创建计算某事的后台任务以及何时完成40%的HUD令人耳目一新,达到了40%的进步.我希望自己清楚明白,如果有人有时间帮助改进我的代码,那么非常感谢任何答案
解决方法 在这种情况下,您可以通过将计数器的更新与UI中的HUD更新分离来解决问题. Apple将此称为WWDC 2012视频 Asynchronous Design Patterns with Blocks,GCD,and XPC中的“异步更新状态”.通常这不是必需的(大部分时间我们异步进行的 *** 作都很慢,以至于我们没有问题),但如果做的事情比UI运行得更快,那么你可以创建这是一个“调度源”.我将用UIProgressVIEw来说明它,但同样适用于任何UI:
// create source for which we'll be incrementing a counter,// and tell it to run the event handler in the main loop// (because we're going to be updating the UI)dispatch_source_t source = dispatch_source_create(disPATCH_SOURCE_TYPE_DATA_ADD,dispatch_get_main_queue());// specify what you want the even handler to do (i.e. update the HUD or progress bar)dispatch_source_set_event_handler(source,^{ self.iterations += dispatch_source_get_data(source); [self.progressVIEw setProgress: (float) self.iterations / kMaxIterations];});// start the dispatch sourcedispatch_resume(source);// Now,initiate the process that will update the sourcedispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAulT,^{ for (long i = 0; i < kMaxIterations; i++) { // presumably,do something meaningful here // Now increment counter (and the event handler will take care of the UI) dispatch_source_merge_data(source,1); } // when all done,cancel the dispatch source dispatch_source_cancel(source);}); 在我的例子中,迭代只是一个很长的属性:
@property (nonatomic) long iterations;
我将kMaxIterations常量定义如下:
static long const kMaxIterations = 10000000l;总结
以上是内存溢出为你收集整理的ios – 如何使用GCD说明后台任务?全部内容,希望文章能够帮你解决ios – 如何使用GCD说明后台任务?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)