在Objective-C中使用TBXML时发生内存泄漏

问题描述:

我是Objective C的新手,但仍不清楚如何使用retain和release。 在下面的代码中,我想使用TBXML来解析XML文件并填充TableView。代码有效,但当我“分析”我的应用时,Xcode说变量name中有内存泄漏。我想我应该在保留它之后释放该变量,但是,无论何时我试图释放该变量,无论我在哪里执行该操作,都会产生错误。我也试图不保留它,但它也产生了一个错误。在Objective-C中使用TBXML时发生内存泄漏

有人能解释一下这里发生了什么吗?

- (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

你的代码看起来不错。看起来你只需要调用''[release release]''你在哪里调用'[newsCategory release]'。所以,如果你不叫'[姓名保留]'你看到一个错误?什么错误?它应该是一个自动释放的对象,所以你不必在这个方法中保留/释放它。你的txxml变量也是如此 - 你不应该保留/释放这个(因为它是自动发布的)。 – Sam

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

但是,您需要将其保留或复制到[NewsCategory initWithCategoryName:] metod中。