0

我正在使用 TouchXML 解析一些 XML,但我遇到了崩溃 -EXC_BAD_ACCESS。我通过反复试验发现,如果我不发布我的 CXMLDocument(我分配的),那么一切都很好。这是我的代码:

- (NSArray *)getLookUps {

    //Do some stuff and then...

    NSData *tempData = [NSURLConnection sendSynchronousRequest:request 
                                                 returningResponse:nil 
                                                             error:nil];



        CXMLDocument *xmlDoc = [[CXMLDocument alloc] initWithData:tempData options:0 error:nil];
        NSDictionary *mappings = [NSDictionary dictionaryWithObject:@"http://****/****" 
                                                             forKey:@"****"];

        NSLog(@"%@", [[NSString alloc] initWithData:tempData encoding:NSUTF8StringEncoding]);
        NSArray *orders = [[xmlDoc rootElement] nodesForXPath:@"//****:Unit" 
                                            namespaceMappings:mappings 
                                                        error:nil];

        NSMutableArray *units = [NSMutableArray arrayWithCapacity:200];

        for (CXMLElement *order in orders) {
            NSArray *nodes = [order children];
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:[nodes count]];

            for (CXMLElement *node in nodes) {
                [dictionary setObject:[node stringValue] forKey:[node name]];
            }
            [units addObject:dictionary];
        }

        //[xmlDoc release];
    return units;
}

见第 2 行最后一行,[xmlDoc release]。我已经对此发表了评论,因为如果我不这样做,它就会崩溃。我究竟做错了什么?谢谢。

4

4 回答 4

1

此错误已报告并在库的较新版本中标记为已修复。

http://code.google.com/p/touchcode/issues/detail?id=35

我还没有测试它是否真的修复了,该 URL 上的评论表明它不是。

在我看来,应该完全避免使用这个库。对于 iOS 应用程序,使用 libxml2 有几个原因:

  • 它经过测试和尝试,彻头彻尾
  • 它快速高效
  • 构建基于节点的 XML 表示可能会使编码更容易,但它会浪费内存,因为您总是将整个文档放在内存中。在解析时,您可能不止一次拥有它。相反,您应该设计代码以使用 libxml2 方法。一旦您开始解析大量文档,您就会同意。
于 2011-10-24T20:28:24.017 回答
1

您可能需要保留您的字典对象,否则它也会在您释放解析器时被释放。尝试更改[units addObject:dictionary];[units addObject:[dictionary retain]];.

另一个想法是将您的 xmlDoc 指针设置为自动释放:

CXMLDocument *xmlDoc = [[[CXMLDocument alloc] initWithData:tempData options:0 error:nil] autorelease];
于 2011-07-17T11:25:47.503 回答
0

我经常使用 TouchXML,而且(幸运的是?)到目前为止我还没有遇到这个问题,但它只是发生了......

我在这里发布了一个解决方案: Memory crash using [CXMLNode nodesForXPath] with namespace mappings

于 2013-09-24T08:03:12.490 回答
0

我在 TouchXML 类“CXMLDocument”中观察到我们在“dealloc”方法中有以下处理。

- (void)dealloc
{
    // Fix for #35 http://code.google.com/p/touchcode/issues/detail?id=35 -- clear up the node objects first (inside a pool so I _know_ they're cleared) and then freeing the document

    @autoreleasepool {

        nodePool = NULL;

    }
    //
    xmlUnlinkNode(_node);
    xmlFreeDoc((xmlDocPtr)_node);
    _node = NULL;
}

我不确定我们为什么在“dealloc”中使用“autoreleasepool”。这是标准编码吗?如果我错了,请纠正我。

于 2015-06-16T12:50:08.213 回答