Memory leak when using TBXML in Objective-C
I'm new to Objective C and am still not very clear about how to use retain and release.
In the following code, I want to use TBXML to parse an XML file and populate a TableView. The code works, but when I "Analyze" my app, Xcode says there are memory leaks in the variable name
. I suppose I should release the variable after retaining it, however, whenever I tried to release it, no matter where I do it, it always produced an error. I also tried NOT to retain it, but it also produced an error.
Can somebody please explain what is happening here?
- (void)loadNews {
TBXML * tbxml = [[TBXML tbxmlWithURL:[NSURL URLWithString:@"http://www.abc/def.xml"]] retain];
// If TBXML found a root node, process element and iterate all children
if (tbxml.rootXMLElement) {
TBXMLElement *categoryElement = [TBXML childElementNamed:@"category" parentElement:[tbxml rootXMLElement]];
do {
NSString *name = [TBXML valueOfAttributeNamed:@"name" forElement:categoryElement];
[name retain]; // Something wrong with this line?
NewsCategory *newsCategory = [[NewsCategory alloc] initWithCategoryName:name];
// get entries in the category
TBXMLElement *entryElement = [TBXML childElement开发者_运维百科Named:@"entry" parentElement: categoryElement];
do {
NSString *title = [TBXML textForElement:[TBXML childElementNamed:@"title" parentElement:entryElement]];
NSString * icon = [TBXML textForElement:[TBXML childElementNamed:@"icon" parentElement:entryElement]];
NSString * link = [TBXML textForElement:[TBXML childElementNamed:@"link" parentElement:entryElement]];
NSString * desc = [TBXML textForElement:[TBXML childElementNamed:@"desc" parentElement:entryElement]];
NewsEntry *newsEntry = [[NewsEntry alloc] init];
newsEntry.title = title;
newsEntry.icon = icon;
newsEntry.link = link;
newsEntry.desc = desc;
[newsCategory addEntry:newsEntry];
[newsEntry release];
} while((entryElement = entryElement->nextSibling));
// save category
[newsData addCategory:newsCategory];
[newsCategory release];
} while((categoryElement = categoryElement->nextSibling));
}
// release resources
[tbxml release];
[newsTableView reloadData];
}
If the guys who created [TBXML valueOfAttributeNamed: forElement:]
followed the naming convention the value should be autoreleased. You do not need to retain it.
However, you need to retain or copy it in the [NewsCategory initWithCategoryName:]
metod.
精彩评论