Reputation: 67
I have a mutablearray that is populated from sqlite db in ios. I have gotten the annotations to load and view properly. My question is how can I write a loop that will add annotations with the size of the array. I have tried the following code and get and display the last entry in the array
NSMutableArray *annotations=[[NSMutableArray alloc] init];
CLLocationCoordinate2D theCoordinate5;
MyAnnotation* myAnnotation5=[[MyAnnotation alloc] init];
for (int i = 0; i < _getDBInfo.count; i++) {
dbInfo *entity = [_getDBInfo objectAtIndex:i];
NSNumber *numlat=[[NSNumber alloc] initWithDouble:[entity.Latitude doubleValue]];
NSNumber *numlon=[[NSNumber alloc] initWithDouble:[entity.Longitude doubleValue]];
NSLog(@"%d",[_getDBInfo count]);
la=[numlat doubleValue];
lo=[numlon doubleValue];
theCoordinate5.latitude=la;
theCoordinate5.longitude=lo;
myAnnotation5.coordinate=theCoordinate5;
myAnnotation5.title=[NSString stringWithFormat:@"%@"entity.EntityNo];
myAnnotation5.subtitle=[NSString stringWithFormat:@"%@",entity.EntityName];
[mapView addAnnotation:myAnnotation5];
[annotations addObject:myAnnotation5];
}
I guess my question is how can I create and add to my view annotation objects based on the count in my array?
Any help is much appreciated.
I am new to iOS as well as programming so please be gentle.
Upvotes: 2
Views: 5266
Reputation: 8808
You only have one myAnnotation5
object. When you set its coordinate
, title
, etc., you are setting it for that instance, which you happen to have added to annotations
multiple times. Hence every entry in annotations
will have the last set of properties you set - since every entry in annotations
is actually the same object.
To remedy this, you need to create your myAnnotation5
object anew each iteration of the loop, i.e.
for (int i = 0; i < _getDBInfo.count; i++) {
MyAnnotation* myAnnotation5=[[MyAnnotation alloc] init];
...
myAnnotation5.coordinate=theCoordinate5;
myAnnotation5.title=[NSString stringWithFormat:@"%@", entity.EntityNo];
myAnnotation5.subtitle=[NSString stringWithFormat:@"%@", entity.EntityName];
...
[mapView addAnnotation:myAnnotation5];
}
Two asides:
MKMapView
has an -annotations
property, there is likely little reason for you to keep your own annotations
array - just keep a reference to mapView
.Upvotes: 3
Reputation:
Move this line:
MyAnnotation* myAnnotation5=[[MyAnnotation alloc] init];
to inside the for-loop just before setting the properties on myAnnotation5
.
The way it is right now, you are creating only one MyAnnotation
object and modifying its properties repeatedly.
Upvotes: 1