Add MKnnotations to MKMapView from NSArray coordinates

I need to add several annotations to MKMapView (an example is one for each city in the country), and I do not want to initialize each CLLocation2D with the latitude and longitude of all cities. I think this is possible with arrays, so this is my code:

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]; } 

Well, everything is fine, if I leave ONE object in NSArrays latit and longit, I have an ONE annotation on the map; but if I add several objects to the assembly applications of arrays, but it fails with EXC_BAD_ACCESS (code = 1 ...). What's the problem or what's the best way to add multiple annotations without redundant code? Thanks!

+4
source share
1 answer

You always use the same annotation object that:

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

Shift it in a for loop or copy it before adding it to the map.

The explanation . This is the annotation property found in the MKAnnotation protocol:

 @property (nonatomic, readonly) CLLocationCoordinate2D coordinate; 

As you can see, this is not copying an object, so if you always add the same annotation, you have duplicate annotations. If you add an annotation with coordinates (20,20) at time 1, then during 2 you change the coordinates of annotations to (40,40) and add them to the map, but this is the same object.

Also, I do not propose placing NSNumber objects in it. Instead, create a unique array and fill it with CLLocation , as they are designed to store coordinates. The CLLocation class has the following property:

 @property(readonly, NS_NONATOMIC_IPHONEONLY) CLLocationCoordinate2D; 

This is also an immutable object, so you need to initialize this property at the time the object is created. Use the initWithLatitude: longitude: method method:

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

So you can write a better version of your code:

 #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]; } 
+3
source

All Articles