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, i.e. 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
精彩评论