iOS在系统空闲时定期执行低优先级任务 [英] iOS Periodically perform a low-priority task while the system is idle

查看:170
本文介绍了iOS在系统空闲时定期执行低优先级任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iOS App开发过程中。我想定期执行低优先级的任务。并且不希望这个任务会影响主程序的工作。实现它的方法是什么?

In the iOS App development process. I want to periodically perform a low priority task. And do not want this task will affect the main program of work. What is the way to achieve it?

现在我使用 timer 来执行定期任务,但经常会发现应用程序不流畅。

Now I use the timer to perform periodical task, but often find the App is not smooth.

低优先级任务有时需要在主线程上运行,例如检查粘贴板,而不是在UI上显示内容。

推荐答案

您必须为此使用Blocks(完成处理程序),它是GCD的一部分。这将远离主线程。

You will have to use Blocks(Completion handlers) for this, it's part of GCD. This will stay away from main thread.

制作一个名为 backgroundClass 的NSObject类。

Make a NSObject class named "backgroundClass".

.h文件

typedef void (^myBlock)(bool success, NSDictionary *dict);

@interface backgroundClass : NSObject

@property (nonatomic, strong)  myBlock completionHandler;

-(void)taskDo:(NSString *)userData block:(myBlock)compblock;

在.m文件中

-(void)taskDo:(NSString *)userData block:(myBlock)compblock{
  // your task here
// it will be performed in background, wont hang your UI. 
// once the task is done call "compBlock" 

compblock(True,@{@"":@""});
}

在您的viewcontroller .m类中

- (void)viewDidLoad {
    [super viewDidLoad];
backgroundClass *bgCall=[backgroundClass new];

 [bgCall taskDo:@"" block:^(bool success, NSDictionary *dict){
// this will be called after task done. it'll pass Dict and Success.    

dispatch_async(dispatch_get_main_queue(), ^{
 // write code here if you need to access main thread and change the UI.
// this will freeze your app a bit.
});

}];
}

这篇关于iOS在系统空闲时定期执行低优先级任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆