2014-01-10 20 views
1

我有一种方法可以在地图中插入注释。该方法由map的委托方法调用。MKAnnotation不会出现在使用NSThread的地图

问题是注释不会出现在地图中。我必须再次触摸地图来显示注释。

插入注释后,我使用[CATRansaction flush],但它不起作用。

上面的代码:

地图委托的方法:

 
- (void) mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{ 

    log(@"region changed"); 

    if (_userRegion.center.latitude) { 
     log(@"Move map. New location: %f X %f", self.mapView.centerCoordinate.latitude, self.mapView.centerCoordinate.longitude); 

     NSDictionary *coordinates = @{ 
             @"latitude": [NSString stringWithFormat:@"%f", self.mapView.centerCoordinate.latitude], 
             @"longitude": [NSString stringWithFormat:@"%f", self.mapView.centerCoordinate.longitude] 
             }; 
     NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(updateMap:) object:coordinates]; 
     [thread start]; 
    } 

    if(_userMenuOpened){ 
     [self closeUserMenu]; 
    } 

    if(_settingsMenuOpened){ 
     [self closeSettingsMenu]; 
    } 

} 

方法插入注释:

 
- (void) updateMap:(NSDictionary *) coordinates { 

    NSArray *annotationsInMap = [self.mapView annotations]; 

    _busStops = [_ws getStations:10 lat:[[coordinates valueForKey:@"latitude"] doubleValue] lng:[[coordinates valueForKey:@"longitude"] doubleValue]]; 

    for(NSString *stop in _busStops) { 

     BOOL inMap = NO; 
     BPBusStopAnnotation *annotation = [[BPBusStopAnnotation alloc] initWithData:stop]; 

     //Se tiver annotation no mapa verifica se os que vem no WS sao os mesmos 
     if(annotationsInMap.count > 0){ 

      for(BPBusStopAnnotation *pt in annotationsInMap){ 
       if(pt && ![pt isKindOfClass:[MKUserLocation class]]){ 

        if([annotation.codigo isEqual:pt.codigo]){ 
         inMap = YES; 
         break; 

        } 
       } 
      } 

     } 

     if (!inMap) { 
      [self.mapView addAnnotation:annotation]; 
     } 

    } 

    [CATransaction flush]; 

} 

感谢的!

+1

相关:http://stackoverflow.com/questions/1995245/iphone-mapview-interrupted – Anna

回答

1

在“updateMap”的方法,我改变

if (!inMap) { 
    [self.mapView addAnnotation:annotation]; 
} 

​​
1

你自己说:这是线程。除了主线程之外,你不能做任何影响接口的事情,这就是问题所在。

(而当你解决这个,如果我是你,我会从未使用NSThread,这是最坏的所有可能的方式做iOS的线程。)

+0

感谢对你的答案@m att,但我该如何解决我的问题? 我需要在该委托方法中调用ws,但是如果我在主线程中这样做,它会冻结屏幕直到完成ws调用。 –

+1

当您想要在后台执行某些操作时,您可以进入后台线程,并且当您想在主线程中执行某些操作时(例如更新界面),可以回到主线程。 – matt

+1

在你继续之前,它可能会帮助你停止并学习iOS中的线程。例如,请参阅[我的书的主题]章节(http://www.apeth.com/iOSBook/ch38.html)。 – matt