Search code examples
iphoneiosasynchronousmkmapviewmapkit

How to add annotations to MKMapView asynchronously?


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

Solution

  • 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