对于iOS,我知道UI的所有更新必须在主线程上完成。 从UI安全读取是否可以从主线程外部进行?
我有一些计算量很大的逻辑,需要使用MKMapView
的{{1}}方法,这需要convertCoordinate
。从主线程外部这样做是否安全?
答案 0 :(得分:1)
是的,您可以进行帧计算或背景中的任何逻辑。但是添加子视图,动画等UI操作必须在主线程中。
CGPoint annPoint = [self.mapView convertCoordinate:coord toPointToView:self.mapView];
mapPic = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic.png"]];
mapPic.frame = CGRectMake(annPoint.x, annPoint.y, 32, 32);
[self.view addSubview:macPic];
可以根据您的要求编写:
- (void)doCalculation
{
//you can use any string instead "com.mycompany.myqueue"
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_async(backgroundQueue, ^{
CGPoint annPoint = [self.mapView convertCoordinate:coord toPointToView:self.mapView];
mapPic = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic.png"]];
mapPic.frame = CGRectMake(annPoint.x, annPoint.y, 32, 32);
dispatch_async(dispatch_get_main_queue(), ^{
[self.view addSubview:macPic];
});
});
}
希望它会有所帮助