NSMutableString内存泄漏

时间:2011-08-29 12:43:50

标签: iphone objective-c nsmutablestring

我在代码enter image description here

中的工具中出现内存泄漏
-(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];

}

这是管理内存的正确方法吗?

2 个答案:

答案 0 :(得分:1)

不是设置自动释放池,而是实际释放字符串,为什么不自己发布呢?如果代理人保留getcat:中的字符串,您只需将其释放:

- (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];
}

看一下getcat:,我发现了一个问题:

[xmlParser parse];
[xmlParser release];

通常,对象需要委托才能从线程返回结果。我假设[xmlParser parse]启动一个线程。您可能不应该在完成之前释放它,即您在parserDidEndDocument:中执行此操作。

然而,这并没有解释许多泄露的字符串。

答案 1 :(得分:0)

我解决了这个问题

漏洞在

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

    currentElement = [elementName copy]; --->始终在此行泄漏但泄漏仪器显示该行

}

  

self.currentElemnt = elementName

替换代码