2013-01-10 13 views
4

我需要在我的MKMapView上添加幾個註釋(一個國家/地區的每個城市的示例),而且我不想初始化每個CLLocation2D的所有城市的經度和緯度。我認爲這是可能的排列,所以這是我的代碼:在NSMapray座標上添加MKAnnotations

NSArray *latit = [[NSArray alloc] initWithObjects:@"20", nil]; // <--- I cannot add more than ONE object 
NSArray *longit = [[NSArray alloc] initWithObjects:@"20", nil]; // <--- I cannot add more than ONE object 

// I want to avoid code like location1.latitude, location2.latitude,... locationN.latitude... 

CLLocationCoordinate2D location; 
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init]; 

for (int i=0; i<[latit count]; i++) { 
    double lat = [[latit objectAtIndex:i] doubleValue]; 
    double lon = [[longit objectAtIndex:i] doubleValue]; 
    location.latitude = lat; 
    location.longitude = lon; 
    annotation.coordinate = location; 
    [map addAnnotation: annotation]; 
} 

好了,所有的權利,如果我離開一個對象在NSArrays latit和longit,我在地圖上一個註釋;但是如果我向數組應用程序構建添加多個對象,但會使用EXC_BAD_ACCESS(代碼= 1 ...)崩潰。有什麼問題,或者什麼是在沒有冗餘代碼的情況下添加多個註釋的最佳方式?謝謝!

回答

3

您正在使用總是相同的註釋對象,這是這樣的:

MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init]; 

取代它在for循環中,或添加到地圖前將其複製。

說明:這是MKAnnotation協議中發現的註解屬性:

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate; 

正如你看到它是不是抄襲的對象,因此,如果您添加總是相同的註解,你將不得不重複的註解。如果您在時間1添加了帶有座標(20,20)的註釋,則在時間2時,您將註釋座標更改爲(40,40)並將其添加到地圖中,但它是同一個對象。

另外我不建議把NSNumber裏面的東西放進去。取而代之的是製作一個獨特的數組,並填充它的CLLocation對象,因爲它們用於存儲座標。該CLLocation類有此屬性:

@property(readonly, NS_NONATOMIC_IPHONEONLY) CLLocationCoordinate2D; 

這是一個不可改變的對象,所以你需要在你創建對象的時刻初始化這個屬性。使用initWithLatitude:經度:方法:

- (id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude; 

所以,你可以寫一個更好版本的代碼:

#define MakeLocation(lat,lon) [[CLLocation alloc]initWithLatitude: lat longitude: lon]; 

NSArray* locations= @[ MakeLocation(20,20) , MakeLocation(40,40) , MakeLocation(60,60) ]; 

for (int i=0; i<[locations count]; i++) { 
    MKPointAnnotation* annotation= [MKPointAnnotation new]; 
    annotation.coordinate= [locations[i] coordinate]; 
    [map addAnnotation: annotation]; 
} 
+0

絕對優雅,和漂亮的解釋。我只需要添加CoreLocation框架,你的代碼是完美的。謝謝! – Huxley