Can someone point me to a leak in this code?

2020-03-30 05:21发布

问题:

DisplayMap.h

#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>


@interface DisplayMap : NSObject <MKAnnotation> {

    CLLocationCoordinate2D coordinate; 
    NSString *title; 
    NSString *subtitle;
}
@property (nonatomic, assign) CLLocationCoordinate2D coordinate; 
@property (nonatomic, copy) NSString *title; 
@property (nonatomic, copy) NSString *subtitle;

@end

DisplayMap.m

#import "DisplayMap.h"


@implementation DisplayMap

@synthesize coordinate,title,subtitle;


-(void)dealloc{
    [title release];
    [super dealloc];
}

@end

I am implementing the above in a map view to show annotations. On the viewdidload, i run through a set of coordinates and display them on the map using the above mentioned annotation class.

for(int i=0;i<[xmlParameter count];i++){
    region.center.latitude=(double)[[[xmlParameter objectAtIndex:i]objectAtIndex:3] doubleValue];
    region.center.longitude =(double) [[[xmlParameter objectAtIndex:i]objectAtIndex:4] doubleValue] ;
    region.span.longitudeDelta = 0.08f;
    region.span.latitudeDelta = 0.08f;
    DisplayMap *ann = [[DisplayMap alloc] init]; 
    ann.title = [[xmlParameter objectAtIndex:i]objectAtIndex:0];
    ann.subtitle = [[xmlParameter objectAtIndex:i]objectAtIndex:1]; 
    ann.coordinate = region.center; 
    [mapView addAnnotation:ann];
    if(i==zoomtoParameter){
        [mapView setRegion:region animated:YES];            
        //showAnnotation=ann;       
        [mapView selectAnnotation:currentAnnotation animated:YES];          
        //[mapView selectAnnotation:ann animated:YES];
    }

    [ann release];
}   

Running with instruments with leaks, says there is a DisplayMap leak for 32Bytes in the viewDidLoad method. I can't figure out how; i am releasing the DisplayMap object right after am done with it.

Any suggestions?

Thanks

回答1:

Your subtitle property is declared with a copy attribute, which means you are responsible for releasing it. The following change to your dealloc method should do the trick:

-(void)dealloc{
    [subtitle release];
    [title release];
    [super dealloc];
}

Edit: To elaborate: Cocoa's memory management rules state that you must release any memory that you alloc, retain or copy. In the case of synthesized properties, this means that you must include the appropriate release messages in your -dealloc method. See my own question on this topic for more details.

In the sample code that you provided, the following line:

ann.subtitle = [[xmlParameter objectAtIndex:i]objectAtIndex:1];

Creates a copy of the indicated object. When you later call [ann release], that copied object will be leaked unless you explicitly release it.