iOS在系统闲置时定期执行低优先级任务

在iOS应用程序开发过程中。 我想定期执行一个低优先级的任务。 而不希望这个任务会影响主要的工作scheme。 有什么办法实现它?

现在我用timer执行定期任务,但是经常发现应用程序不顺畅。

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

你将不得不使用块(完成处理程序),这是GCD的一部分。 这将远离主线程。

制作一个名为“ backgroundClass ”的NSObject类。

在.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. }); }]; }