Reputation: 375
I'm using the following code to make a pin for annotation:
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
annView.pinColor = MKPinAnnotationColorGreen;
annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
Everything works perfectly, however Analyze in XCode shows memory leak in this code. In fact, I see it too cos I allocated object and then did not released it. How can I avoid memory leak here?
Upvotes: 0
Views: 1218
Reputation: 4932
You didn't wrote, but I think analyzer tells you what it leaks here:
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]
initWithAnnotation:annotation
reuseIdentifier:@"currentloc"];
Thats because you need autorelease item:
MKPinAnnotationView *annView=[[[MKPinAnnotationView alloc]
initWithAnnotation:annotation
reuseIdentifier:@"currentloc"] autorelease];
UPDATE
Also you don't reuse created annotations, try do this:
MKPinAnnotationView *annView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"currentloc"];
if(annView == nil)
annView = annView=[[[MKPinAnnotationView alloc]
initWithAnnotation:annotation
reuseIdentifier:@"currentloc"] autorelease];
Upvotes: 3
Reputation: 46027
In fact, I see it too cos I allocated object and then did not released it.
You are right about the reason of the leak. If you need to return an alloced object from a method then the idea is to autorelease that.
- (MyClass *)getObject {
MyClass *obj = [[MyClass alloc] init];
return [obj autorelease];
}
Then you will retain the returned object in caller if needed.
Or name the method in such a way that it is clear that the returned object need to be released in caller. And then release in the caller.
Upvotes: 1