2011-08-19 51 views
3

該函數接受一組經緯度對。它將它們全部轉換成MKAnnotations,然後對於地圖上當前存在的每個註釋,它檢查它是否存在於新的註釋集合中。如果它存在,則按原樣保留註釋,否則將其刪除。MKAnnotation去除(處理器重)

然後,對於每個新註釋,它會檢查它是否當前在地圖上;如果是,則保留它,否則將其刪除。

這顯然是非常密集的,我想知道是否有更快的方法做到這一點?

- (void)setAnnotationWithArray:(NSArray *)array { 
    static BOOL processing = NO; 
    if (processing) { 
     return; 
    } 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     processing = YES; 


     NSMutableArray *annotationsArray = [NSMutableArray arrayWithCapacity:[array count]]; 
     NSMutableArray *annotationsToRemove = [NSMutableArray array]; 

     for (NSDictionary *dict in array) { 
      NSString *latStr = [dict objectForKey:@"Latitude"]; 
      NSString *lonStr = [dict objectForKey:@"Longitude"]; 
      NSString *title = [dict objectForKey:@"Location"]; 

      double lat = [latStr doubleValue]; 
      double lon = [lonStr doubleValue]; 


      CLLocationCoordinate2D location; 
      location.latitude = lat; 
      location.longitude = lon; 

      MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:title andCoordinate:location]; 
      [annotationsArray addObject:newAnnotation]; 
      [newAnnotation release]; 
     } 

     for (id<MKAnnotation> oldAnnotation in [mv annotations]) { 
      CLLocationCoordinate2D oldCoordinate = [oldAnnotation coordinate]; 

      BOOL exists = NO; 
      for (MapViewAnnotation *newAnnontation in annotationsArray) { 
       CLLocationCoordinate2D newCoordinate = [newAnnontation coordinate]; 
       if ((newCoordinate.latitude == oldCoordinate.latitude) 
        && (newCoordinate.longitude == oldCoordinate.longitude)) { 
        exists = YES; 
        break; 
       } 
      } 

      if (!exists) { 
       [annotationsToRemove addObject:oldAnnotation]; 
      } 
     } 


     [annotationsArray removeObjectsInArray:[mv annotations]]; 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      processing = NO; 
      [mv removeAnnotations:annotationsToRemove]; 
      [mv addAnnotations:annotationsArray]; 
     }); 
    }); 



} 
+0

你確定行'[annotationsArray removeObjectsInArray:[mv annotations]];'實際上有效嗎?您正在創建_new_註釋對象並將其放入annotationsArray中。除非你按照Zoleas的說法實現了'isEqual',否則這些新的對象不會與'[mv annotations]'中的那些'相等'(即使屬性值匹配)。如果該行不執行任何操作,則每次調用此方法時都會在地圖上添加註釋的重複副本(可能導致性能下降)。 – Anna

回答

3

你可以使用removeObjectsInArray :(NSArray *)。

例如:

NSMutableArray *annotationsToRemove = [[NSMutableArray alloc] initWithArray:[mapView annotations]]; 
[annotationsToRemove removeObjectsInArray:annotationsArray]; 
NSMutableArray *annotationsToAdd = [[NSMutableArray alloc] initWithArray:annotationsArray]; 
[annotationsToAdd removeObjectsInArray:[mapView annotations]]; 

它假定您的註解實現哈希和isEqual:方法,但應該更加高效。