我有很多注释要添加到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<MKAnnotation>)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;
}
答案 0 :(得分:2)
您可以使用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 and threading
答案 1 :(得分:2)
更好的&amp;更简单,检查-[MKMapView addAnnotations:]
批量添加,而不需要重复计算每个注释的开销。