I need to add on my MKMapView several annotations (example one for each city in a country) and I don’t want to initializate every CLLocation2D with latitude and longitude of all cities. I think it 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];
}
Ok, its all right if I leave ONE object in the NSArrays latit and longit, I have ONE annotation on the map; but if I add more than one object to the arrays app builds but crashes with EXC_BAD_ACCESS (code=1…). What’s the problem, or what the best way to add several annotations without redundant code? Thank you!
You are using always the same annotation object, which is this:
Displace it in the for loop, or copy it before adding to the map.
Explanation: This is the annotation property found in the
MKAnnotationprotocol:As you see it isn’t copying the object, so if you add always the same annotation you would have duplicate annotations. If you add an annotation with coordinates (20,20) at time 1, then at time 2 you change the annotation coordinates to (40,40) and add it to the map, but it’s the same object.
Also I don’t suggest to put
NSNumberobjects inside it. Instead make an unique array and fill it of CLLocation objects, as they’re made to store coordinates. TheCLLocationclass has this property:It’s an immutable object too, so you need to initialise this property at the moment you create the object. Use the initWithLatitude:longitude: method :
So you could write a better version of your code: