0

我是 Objective C 的新手,仍然不太清楚如何使用保留和释放。在下面的代码中,我想使用 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];
}
4

1 回答 1

-1

如果创建的人[TBXML valueOfAttributeNamed: forElement:]遵循命名约定,则应该自动释放该值。您不需要保留它。

但是,您需要在方法中保留或复制它[NewsCategory initWithCategoryName:]

于 2011-09-30T13:51:13.450 回答