在iOS应用程序开发过程中。我想定期执行一个低优先级的任务。而且不想这个任务会影响到主程序的工作。实现这一目标的途径是什么?
现在我用timer来执行周期性的任务,但是经常发现应用程序并不流畅。
低优先级任务有时需要在主线程上运行,例如检查面板,而不是在UI.上显示内容。
发布于 2017-11-02 05:45:41
为此,必须使用块(完成处理程序),这是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.
});
}];
}https://stackoverflow.com/questions/47066887
复制相似问题