解析XML时数组被覆盖(Objective-C)

问题描述:

我正在使用TBXML解析器,但遇到一些困难。解析XML时数组被覆盖(Objective-C)

我使用以下代码将产品对象中的数据添加到名为laarzen的MutableArray。

- (void)loadURL { 
    // Load and parse an xml string 
    Products *product = [[Products alloc] init]; 
    tbxml = [[TBXML alloc] initWithURL:[NSURL URLWithString:@"url..."]]; 

    // If TBXML found a root node, process element and iterate all children 

    // Obtain root element 
    TBXMLElement * root = tbxml.rootXMLElement; 

    // if root element is valid 
    if (root) { 
     // search for the first category element within the root element's children 

     TBXMLElement * Category = [TBXML childElementNamed:@"Category" parentElement:root]; 
     Products *product = [[Products alloc] init]; 
     // if an author element was found 
     while (Category!= nil) { 

      // instantiate an author object 


      // get the name attribute from the author element 
      product.category = [TBXML valueOfAttributeNamed:@"DisplayName" forElement:Category]; 

      // search the author's child elements for a book element 
      TBXMLElement *xmlProduct = [TBXML childElementNamed:@"Product" parentElement:Category]; 
      int i; 
      i=0; 
      // if a book element was found 
      while (xmlProduct != nil) { 
    // extract the title attribute from the book element 
        product.productId = [TBXML valueOfAttributeNamed:@"Id" forElement:xmlProduct]; 

        // extract the title attribute from the book element 
        NSString * price = [TBXML valueOfAttributeNamed:@"Price" forElement:xmlProduct]; 

        // if we found a price 
        if (price != nil) { 
         // obtain the price from the book element 
         product.price = [NSNumber numberWithFloat:[price floatValue]]; 
        } 



        // add the book object to the author's books array and release the resource 
        [laarzen addObject:product]; 

// find the next sibling element named "book" 
       xmlProduct = [TBXML nextSiblingNamed:@"Product" searchFromElement:xmlProduct]; 
      } 

      // add our author object to the authors array and release the resource 


      // find the next sibling element named "author" 
      Category = [TBXML nextSiblingNamed:@"Category" searchFromElement:Category]; 
     } 

    } 


    // release resources 
    [tbxml release]; 
    [product release]; 
} 

由于某种原因,从xml解析出的最后一个节点会覆盖数组中的所有条目。即如果最后的价格是39,99,则阵列中的价格将是39,99。

在我的viewDidLoad我正在分配laarzen如下:

laarzen = [[NSMutableArray alloc] init]; 

在我的dealloc我又释放出来。

在头文件中我做了以下内容:

NSMutableArray *laarzen; 
@property (nonatomic, retain) NSMutableArray *laarzen; 

这可能会是一个记忆的问题,但我只是没有看到它。

THNX!

除非您每次制作新产品对象,否则您只是在数组中存储大量对同一产品对象的引用 - 因此价格看起来相同,因为它们都是同一产品。

+0

哇,我觉得愚蠢......可能编码为长..在迭代中放置产品的分配,它的工作! Thnx男人! – Jos

我没有看到为每个产品创建新产品的位置,这听起来像您只有一个产品实例,并且最终只是一遍又一遍地更新同一个产品。