2013-09-24 21 views
0

在我正在處理的一個應用中,用戶被導向按下按鈕以將MKAnnotations拖放到地圖上。當引腳被添加到didAddAnnotationViews時,它們會丟棄2或3個引腳,每個引腳都被保存到@property中,因爲我稍後需要引用它,並且我需要知道它是哪個引腳 - 引腳1,2或3 (它們被丟棄的順序)。MKAnnotationView正在失去對MKAnnotation的引用

我正在使用自定義的MKAnnotation和MKAnnotationView類爲每個註釋添加幾個NSString,我不確定這是否重要。

我創建3個屬性是這樣的:

@property (nonatomic, strong) CustomAnnotationView *ann1; 
@property (nonatomic, strong) CustomAnnotationView *ann2; 
@property (nonatomic, strong) CustomAnnotationView *ann3; 

這裏是我的didAddAnnotationViews

- (void)mapView:(MKMapView *)aMapView didAddAnnotationViews:(NSArray *)views 
{ 
    for(MKAnnotationView *view in views) 
    { 
     if(![view.annotation isKindOfClass:[MKUserLocation class]]) 
     { 
      CustomAnnotationView *newAnnView = (CustomAnnotationView*)view; 

      if(newAnnView.type == CustomType1) 
      { 
       ann1 = newAnnView; 
      } 
      else if(newAnnView.type == CustomType2) 
      { 
       ann2 = newAnnView; 
      } 
      else if(newAnnView.type == CustomType3) 
      { 
       ann3 = newAnnView; 
      } 
     } 
    } 
} 

而且,這裏是我的viewForAnnotation方法:

- (MKAnnotationView *)mapView:(MKMapView *)pMapView viewForAnnotation:(id <MKAnnotation>)annotation 
{ 
    if([annotation class] == MKUserLocation.class) 
    { 
     return nil; 
    } 

    CustomAnnotationView *annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"WayPoint"]; 

    annotationView.canShowCallout = YES; 

    annotationView.draggable = YES; 
    [annotationView setSelected:YES animated:YES]; 

    [annotationView setRightCalloutAccessoryView:customCalloutButton]; 

    return annotationView; 
} 

現在,最終,我需要保存這些註釋的座標,這裏是出錯的地方。有時候,但只有一段時間,ann1.annotation.coordinate.latitudeann1.annotation.coordinate.longitude都是0.0(這種情況發生在ann1,ann2或ann3上,僅以ann1爲例)!這是爲什麼發生?我有一種感覺,它與對象引用問題有關,因爲MKAnnotationView仍然完好無損,但註釋已被清除。也許我用ann1 = newAnnView分配引用是不好的?我應該用viewForAnnotation

有沒有人看到我做錯了什麼?

UPDATE

我看了看我的MKAnnotation子類,我注意到,當我根據文檔定義座標財產,我是不是在我的實現文件@synthesizing它。我現在補充說,我還沒有能夠複製這個問題呢,如果這最終成爲「修復」,我仍然很困惑爲什麼我的代碼大部分時間沒有@synthesize 。也許我沒有真正解決這個問題,而且我後來爲失望而自責。

回答

1

我不認爲你;應該使用didAddAnnotationViews那樣的。通常情況下,流程如下:

  1. 創建一個MKAnnotation,或者你對它的子類
  2. 的實例分配你提到的字符串
  3. 呼叫[mapView addAnnotation:myAnnotation]
  4. viewForAnnotation創建MKAnnotationView(或CustomAnnotationView(基於annotation作爲參數提供
  5. 當您需要保存座標時,您可以循環訪問mapView.annotations陣列,或者如果您保存了稱爲ann1,ann2,ann3的re3變量可以逐個保存它們。

當然,如果你找到了更好的方法,或者這不適合你的應用程序中的其他東西,你不需要使用它,但這是迄今爲止唯一的流程。

+1

我建議你把這個改成通常的方法。存儲'註釋'以便重用,而不是視圖。在MVC範式視圖中不包含數據,它們只是顯示有關模型的內容。和MKAnnotations是你在這種情況下的模型。 – Craig

+0

^上面的評論是很久很久以前=)爲我解決了這個問題。存儲模型,而不是視圖,杜。當我還是一個obj-c新手時,這又回來了。 – DiscDev