如何异步添加注释到MKMapView?

我有很多注释要添加到mkmapview中。 当我添加注释时,应用程序会冻结很短的时间。 我已经明白主线程是唯一允许添加UI来查看的线程,如果这是真的,如何让这个操作不冻结应用程序?

// in viewdidLoad for (NSManagedObject *object in requestResults) { CustomAnnotation *customAnnotation = [[CustomAnnotation alloc] init]; customAnnotation.title = object.title; customAnnotation.coordinate = CLLocationCoordinate2DMake([object.latitude doubleValue], [object.longitude doubleValue]); [_mapView addAnnotation:customAnnotation]; } } // end viewdidload - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation { // shows the annotation with a custom image MKPinAnnotationView *customPinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"mapAnnotation"]; CustomAnnotation *customAnnotation = (id) annotation; customPinView.image = [UIImage imageNamed:@"green"]; return customPinView; } 

您可以使用Grand Central Dispatch – GCD执行此操作。

试试:

 - (void)viewDidLoad { dispatch_async(dispatch_get_global_queue(0, 0), ^{ for (NSManagedObject *object in requestResults) { CustomAnnotation *customAnnotation = [[CustomAnnotation alloc] init]; customAnnotation.title = object.title; customAnnotation.coordinate = CLLocationCoordinate2DMake([object.latitude doubleValue], [object.longitude doubleValue]); dispatch_async(dispatch_get_main_queue(), ^{ [_mapView addAnnotation:customAnnotation]; }); } }); } 

这是一个很好的教程: GCD和线程

更好更简单,检查-[MKMapView addAnnotations:]批量添加,而不需要重新计算每个单独注释的开销。