i’m trying to develop my first simple app for iphone using the MapKit. I’m now able to show multiple annotations on the map by this simple code. MyAnnotation is the class who generate the annotation and initWithInfo is a method who set the coordinates and the titles.
//the first annotation
theCoordinate.latitude = 0.000;
theCoordinate.longitude = 0.000;
MyAnnotation *myAnnotation1 = [MyAnnotation alloc];
[myAnnotation1 initWithInfo:theCoordinate:@"Title":@"Subtitle"];
[self.mapAnnotations insertObject:myAnnotation1 atIndex:0];
[myAnnotation1 release];
//the second annotation
theCoordinate.latitude = 0.000;
theCoordinate.longitude = 0.000;
MyAnnotation *myAnnotation2 = [MyAnnotation alloc];
[myAnnotation2 initWithInfo:theCoordinate:@"Title":@"Subtitle"];
[self.mapAnnotations insertObject:myAnnotation2 atIndex:0];
[myAnnotation2 release];
The above code needs to create a different MyAnnotation object for each annotation but i will need to generate them inside a cycle so this way is not so good.
In order to generate as many annotation as i want without the limit of create an object with an unique name i tried the following code and it works fine.
CLLocationCoordinate2D theCoordinate;
//the first annotation
theCoordinate.latitude = 0.000;
theCoordinate.longitude = 0.000;
[self.mapAnnotations insertObject:[[MyAnnotation alloc] initWithInfo:theCoordinate:@"Title":@"Subtitle"] atIndex:0];
//the second annotation
theCoordinate.latitude = 0.000;
theCoordinate.longitude = 0.000;
[self.mapAnnotations insertObject:[[MyAnnotation alloc] initWithInfo:theCoordinate:@"Title":@"Subtitle"] atIndex:1];
Now the easy question is: is it a correct way to proceed? Does this code can cause any kind of problem?
Thanks in advance from a newbie objective-c (wanna be) programmer.
Yes, the major problem is that the second code snippet has added memory leaks to your application. The other is that it won’t compile.
When you add an object to a collection its retain count is increased, which means that your line
should be written as
Pay attention to two things:
Hope this helps!