Reputation: 10432
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;
}
Upvotes: 3
Views: 3068
Reputation: 5128
Even better & simpler, check out -[MKMapView addAnnotations:]
to bulk add without the recalculation overhead of each individual annotation.
Upvotes: 2
Reputation: 107131
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
Upvotes: 2