我是Objective C的新手,我仍然不太清楚如何使用retain和release。
在下面的代码中,我想使用TBXML来解析XML文件并填充TableView。代码有效,但当我“分析”我的应用程序时,Xcode表示变量name
中存在内存泄漏。我想我应该在保留它之后释放它,但是,每当我试图释放它时,无论我在哪里,它总是会产生错误。我也试过不保留它,但它也产生了一个错误。
有人可以解释一下这里发生了什么吗?
- (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 childElementNamed:@"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];
}
答案 0 :(得分:-1)
如果创建[TBXML valueOfAttributeNamed: forElement:]
的人遵循命名约定,则值应自动释放。你不需要保留它。
但是,您需要在[NewsCategory initWithCategoryName:]
metod中保留或复制它。