1

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

现在我用timer来执行周期性任务,但经常发现 App 不流畅。

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

4

1 回答 1

0

为此,您将不得不使用块(完成处理程序),它是 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,@{@"":@""});
}

在您的视图控制器 .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.
});

}];
}
于 2017-11-02T05:45:41.120 回答