0

我正在使用 TBXML 解析器,但遇到了一些困难。

我使用以下代码将产品对象中的数据添加到名为 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;

这可能是一个内存问题,但我只是没有看到它。

太好了!

4

2 回答 2

5

除非您每次都创建一个新产品对象,否则您只是在数组中存储大量对同一产品对象的引用 - 因此价格似乎相同,因为它们都是相同的产品。

于 2011-07-04T20:47:40.060 回答
1

我看不到你在哪里为每个项目创建一个新产品,听起来你只有一个产品实例,最终只是一遍又一遍地更新同一个。

于 2011-07-04T20:48:49.687 回答