我正在使用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];
答案 0 :(得分:0)
[blogEntries addObject:[blogItem copy]];
这是您的错误:您不需要复制blogItem
,addObject:
实际上会retain
其参数,以便您可以在之后安全地致电[blogItem release];
。
你很可能也不应该return [blogEntries copy]
,只返回blogEntries
:这是常见的编程习惯,其名称不包含'copy'或'create'的方法会返回自动释放的值,例如因为当你完成它们时你不需要释放它们。
总结一下,我会选择:
-(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"];