2013-05-14 30 views
3

我有很多注释要添加到mkmapview。当我添加注释时,应用程序会在短时间内冻结。我明白,主线程是允许添加用户界面来查看的唯一线程,如果这是真的,我如何让这个操作不冻结应用程序?如何异步添加批注到MKMapView?

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

使用线程或GCD – Divyu 2013-05-14 08:15:25

回答

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

+0

此代码不会停止应用程序冻结。 – 2014-02-10 17:51:50

+0

@LucioFonseca:这是OP的工作,这就是为什么他接受它。你的情况会有所不同,发现在指责之前。 – 2014-02-11 04:31:34

2

更妙&简单,看看-[MKMapView addAnnotations:]批量添加不每一个人注释的重新计算开销。