简体   繁体   中英

NSMutableString memory leak

I am getting memory leak in instruments in the code 在此处输入图片说明

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
       NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

     NSMutableString * res = [[[NSMutableString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]autorelease];
     [webData release];
    [connection release];
        [res replaceOccurrencesOfString:@"&" withString:@"&" options:NSCaseInsensitiveSearch range:(NSRange){0,[res length]}];
    [delegate getcat:res];

    [pool drain];
}



- (void)getcat:(NSString*)xml
{

if (xmlParser) {

    [xmlParser release];
}
Cid = [[NSMutableArray alloc] init];
Categories = [[NSMutableArray alloc] init];

NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];
xmlParser = [[NSXMLParser alloc] initWithData:data];

[xmlParser setDelegate:self];

[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];
[xmlParser release];

}

Is this the correct way to manage memory?

Instead of setting up an autorelease pool, which will actually release the string, why don't you just release it yourself? If the delegate retains the string in getcat: , you can simply release it:

- (void) connectionDidFinishLoading: (NSURLConnection *) connection
{
    // Omit the autorelease pool.

    NSMutableString * res = [[NSMutableString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    [webData release];
    [connection release];
    [res replaceOccurrencesOfString:@"&" withString:@"&" options:NSCaseInsensitiveSearch range:NSMakeRange(0, res.length)];
    [delegate getcat:res];
    [res release];
}

Taking a look at getcat: , I see a problem:

[xmlParser parse];
[xmlParser release];

Usually, objects need a delegate to return results from a thread. I assume that [xmlParser parse] starts a thread. You should probably not release it before it is finished, ie you do that in parserDidEndDocument: .

This does however not explain the many leaked strings.

I fixed this issue

The leak is in

  • (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

    currentElement = [elementName copy]; --->Always leaking in this line But leak instrument show that line

}

replace the code with self.currentElemnt=elementName

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