0

我正在使用 TouchXML 来解析 XML。虽然我在“配置文件”模式下运行相同。我可以看到内存泄漏。我该如何解决这个问题?

-(NSMutableArray *) grabXML:(NSData *)xmlData andQuery:(NSString *)query {  
    NSMutableArray *blogEntries = [[[NSMutableArray alloc] init] autorelease];  
    CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithData:xmlData options:0 error:nil] autorelease];
    NSArray *resultNodes = [rssParser nodesForXPath:query error:nil];
    for (CXMLElement *resultElement in resultNodes) {
        NSMutableDictionary *blogItem = [[NSMutableDictionary alloc] init];
        int counter;
        for(counter = 0; counter < [resultElement childCount]; counter++) {
            [blogItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
        }
        for( int i = 0; i < [[resultElement attributes] count]; i++) {
            CXMLNode *node = [[resultElement attributes] objectAtIndex:i];
            [blogItem setObject:[[resultElement attributeForName:[node name]] stringValue] forKey:[node name]];
        }
        [blogEntries addObject:[blogItem copy]];
        [blogItem release];
    }
    return [blogEntries copy];
}

我以下面提到的格式调用上述方法。

NSMutableArray *arr = [[self grabXML:responseData andQuery:@"//wsCheneliereResult"] autorelease];
4

1 回答 1

0
[blogEntries addObject:[blogItem copy]];

这是你的错误:你不需要复制blogItem,addObject:实际上retain它的参数,这样你就可以安全地[blogItem release];之后调用。

而且您很可能也不应该这样做return [blogEntries copy],并且只返回blogEntries:这是常见的编程习惯,名称不包含“复制”或“创建”的方法返回自动释放的值,例如您不需要在完成时释放它们他们。

总而言之,我会选择:

-(NSMutableArray *) grabXML:(NSData *)xmlData andQuery:(NSString *)query {  
    NSMutableArray *blogEntries = [[[NSMutableArray alloc] init] autorelease];  
    CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithData:xmlData options:0 error:nil] autorelease];
    NSArray *resultNodes = [rssParser nodesForXPath:query error:nil];
    for (CXMLElement *resultElement in resultNodes) {
        NSMutableDictionary *blogItem = [[NSMutableDictionary alloc] init];
        int counter;
        for(counter = 0; counter < [resultElement childCount]; counter++) {
            [blogItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
        }
        for( int i = 0; i < [[resultElement attributes] count]; i++) {
            CXMLNode *node = [[resultElement attributes] objectAtIndex:i];
            [blogItem setObject:[[resultElement attributeForName:[node name]] stringValue] forKey:[node name]];
        }
        [blogEntries addObject:blogItem];
        [blogItem release];
    }
    return blogEntries;
}

NSMutableArray *arr = [self grabXML:responseData andQuery:@"//wsCheneliereResult"];
于 2012-08-21T15:34:37.097 回答