-(void) test{
for(Person *person in persons){
__block CGPoint point;
dispatch_async(dispatch_get_main_queue(), ^{
point = [self.myview personToPoint:person];
});
usePoint(point); // take a long time to run
}
}
我需要在主队列中运行personToPoint()
来获取该点,并且usePoint()
方法不需要在主队列中运行并且需要很长时间才能运行。但是,在运行usePoint(point)
时,由于使用了dispatch_async,因此尚未为point指定值。如果使用dispatch_sync方法,程序将被阻止。如何在分配后使用点?
更新: 如何实现以下代码的模式:
-(void) test{
NSMutableArray *points = [NSMutableArray array];
for(Person *person in persons){
__block CGPoint point;
dispatch_async(dispatch_get_main_queue(), ^{
point = [self.myview personToPoint:person];
[points addObject:point];
});
}
usePoint(points); // take a long time to run
}
答案 0 :(得分:1)
以下内容可行。您也可以将整个for循环放在一个dispatch_async()中,让主线程立即调度所有的usePoint()函数。
-(void) test{
for(Person *person in persons){
dispatch_async(dispatch_get_main_queue(), ^{
CGPoint point = [self.myview personToPoint:person];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
usePoint(point); // take a long time to run
});
});
}
}
更新问题的解决方案:
您使用与上面建议相同的基本模式。也就是说,您需要将主线程上需要执行的操作分配给主线程,然后将调度嵌套回主线程调度内的默认工作队列。因此,当主线程完成其工作时,它将发送耗时的部分以在其他地方完成。
-(void) test{
dispatch_async(dispatch_get_main_queue(), ^{
NSMutableArray *points = [NSMutableArray array];
for (Person *person in persons){
CGPoint point = [self.myview personToPoint:person];
[points addObject:[NSValue valueWithCGPoint:point]];
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
usePoint(points); // take a long time to run
});
});
}
请注意,代码中存在错误,因为您无法将CGPoint
添加到NSArray
,因为它们不是对象。您必须将它们包装在NSValue
中,然后在usePoint()
中打开它们。我使用了仅适用于iOS的NSValue
扩展程序。在Mac OS X上,您需要将其替换为[NSValue valueWithPoint:NSPointToCGPoint(point)]
。