需求:要在某个网络请求或者使用CALayer绘制之后再做处理操作
举个栗子🌰:
// 正常情况下不作任何处理,在第1行代码里面的绘制操作(假如有...)还没有完成就会执行第2行代码,导致后面的代码先执行,可能造成无数据显示
self.staveView.rowArray = [StaveJsonManager staveRowModelArrayWithJSONString:self.questionModel.score_data];
NSLog(@"操作1");
解决方案1:
// 使用同步栅栏函数,这样在绘制完成之前是不会执行后面的代码的,完成了需求
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
dispatch_barrier_sync(_queue, ^{
NSLog(@"操作1");
self.staveView.rowArray = [StaveJsonManager staveRowModelArrayWithJSONString:self.questionModel.score_data];
});
NSLog(@"操作2");
写在后面(总结):
- 同步栅格函数
dispatch_barrier_sync会等函数体内的任务执行完毕后,才会继续执行下面的代码;
- 异步栅格函数
dispatch_barrier_async不会等函数体内的任务执行完毕,会顺序执行下面的代码;
解决方案2:
// 使用 CFRunLoopRef函数
CFRunLoopRef ref = CFRunLoopGetCurrent();//获取线程runloop
self.staveView.rowArray = [StaveJsonManager staveRowModelArrayWithJSONString:self.questionModel.score_data];
CFRunLoopRun();//调用runloop阻塞
CFRunLoopStop(ref);//取消阻塞
网友评论