iphone - 如何给MKMapView异步添加注解?

标签 iphone ios asynchronous mkmapview mapkit

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

最佳答案

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

关于iphone - 如何给MKMapView异步添加注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16537949/

相关文章:

iphone - iOS5锁屏后如何继续播放视频音轨?

ios - 垂直滚动 Collection View Inside Table View cell

android - 开源用户安全/密码方案

c# - 执行多个CMD任务并异步更新

iphone - 如果应用程序未通过点击 'View' 按钮启动,则检索最新的推送通知

iphone - iOS7 中 UISearchBar 委托(delegate)方法仅调用一次

ios - 如何重置 iOS 9 通用链接设置?

jquery - 从异步函数中向函数返回 true

c# - 如何同步运行延续任务?

iphone - 未调用委托(delegate)方法 "clickedButtonAtIndex:"