2011-09-30 108 views
0

我是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

回答

-1

如果創建[TBXML valueOfAttributeNamed: forElement:]的人遵循命名約定,則應該自動發佈該值。你不需要保留它。

但是,您需要將其保留或複製到[NewsCategory initWithCategoryName:] metod中。

相關問題