在 iOS 上,可以在主线程之外读取 UI 吗?
On iOS, is it okay to read the UI outside of the main thread?
使用 iOS,我知道 UI 的所有 更新 必须在主线程上完成。 从 UI 中读取 从主线程外部安全地执行吗?
我有一些计算量大的逻辑需要使用 MKMapView
的 convertCoordinate
方法,这需要 toPointToView: UIView
。从主线程外部执行此操作安全吗?
是的,您可以在后台进行帧计算或任何逻辑。但是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];
});
});
}
希望对您有所帮助
使用 iOS,我知道 UI 的所有 更新 必须在主线程上完成。 从 UI 中读取 从主线程外部安全地执行吗?
我有一些计算量大的逻辑需要使用 MKMapView
的 convertCoordinate
方法,这需要 toPointToView: UIView
。从主线程外部执行此操作安全吗?
是的,您可以在后台进行帧计算或任何逻辑。但是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];
});
});
}
希望对您有所帮助