简体   繁体   中英

iphone: How to solve NSArray memory Leak?

I am releasing NSArray and NSMutableArray but its show memory leak. while ZoneData code is like this

-(ZoneData*) initWithZoneName:(NSString *)zoneNameIn SdName:(NSString *)sdNameIn eCount:(NSString *)eCountIn iCount:(NSString *)iCountIn StandLat:(NSString *)standLatIn StandLong:(NSString *)standLongIn
{
    self = [super init];
    if (self)
    {
        zoneName = [zoneNameIn copy];
        lsdName = [sdNameIn copy];

        leCount = [eCountIn intValue];
        liCount = [iCountIn intValue];
        standLat =  [standLatIn copy];
        standLong = [standLongIn copy];     
    }

    return self;    
}

在此处输入图片说明

how to solve this?

The problem is your instance variables. In your -init , you are correctly assigning them to copies of the strings from the array. However, you need t also release them in -dealloc .

-(void) dealloc
{
    [zoneName release];
    [lsdName release];
    [standLat release];
    [standLong release];
    [super dealloc];
} 

Now, you may be asking why the leaks tool is telling you the leaks are where you create the NSArray with the strings in it instead of the init method. The reason is that -copy for immutable objects is optimised to do nothing except send retain to self . So those copies you have as instance variables are in reality the same objects as was created by -componentsSeparatedByString:

componentsSeparatedByString: returns an autoreleased NSArray . You are not supposed to release that yourself, but the closest NSAutoreleasePool will do that for you. In line 61 you are overreleasing the array.

If you are concerned about the memory usage while performing the loop you can clear autoreleased objects in each iteration of the loop:

for (...)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // your loop contents.

    [pool drain];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM