【问题标题】:How to add annotations to MKMapView asynchronously?如何异步向 MKMapView 添加注释?
【发布时间】:2013-05-14 08:02:17
【问题描述】:

我有很多注释要添加到 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;
}

【问题讨论】:

    标签: iphone ios asynchronous mkmapview mapkit


    【解决方案1】:

    您可以使用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

    【讨论】:

    • @LucioFonseca:这适用于 OP,这就是他接受它的原因。你的情况会有所不同,在责备之前发现这一点。
    【解决方案2】:

    更好、更简单,查看-[MKMapView addAnnotations:] 进行批量添加,无需重新计算每个注释的开销。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      相关资源
      最近更新 更多