How to add annotations to MKMapView asynchronously?

微笑、不失礼 提交于 2019-12-22 09:57:41

问题


I have a lot of annotations to be added to a mkmapview. When i add the annotations, the app freezes for a short period of time. I have understand that the main thread is the only thread allowed to add UI to view, if this is true, how to i make this operation not freeze the app?

// 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;
}

回答1:


You can use Grand Central Dispatch - GCD for doing this.

Try with:

- (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];
        });
     }
  });
}

This is a nice tutorial: GCD and threading




回答2:


Even better & simpler, check out -[MKMapView addAnnotations:] to bulk add without the recalculation overhead of each individual annotation.



来源:https://stackoverflow.com/questions/16537949/how-to-add-annotations-to-mkmapview-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!