发布Xmlparser和NSXMLParser对象

时间:2011-01-15 12:35:40

标签: objective-c memory-management

如何在下面的函数中安全地释放变量xmlParser和parser?

- (id)callRestService: (NSString *) methodName : (NSDictionary *) params
{
    NSURL *url=[self getRestUrl: methodName : params];
    XmlParser *xmlParser = [[XmlParser alloc] init];

    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    [parser setDelegate:xmlParser];
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    [parser parse];
    [parser setDelegate:nil];



    return xmlParser.dictionaryArray;
}

1 个答案:

答案 0 :(得分:1)

有两种方法:

- (id)callRestService: (NSString *) methodName : (NSDictionary *) params
{
    NSURL *url=[self getRestUrl: methodName : params];
    XmlParser *xmlParser = [[[XmlParser alloc] init] autorelease]; // !!!

    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    [parser setDelegate:xmlParser];
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    [parser parse];
    [parser setDelegate:nil];
    [parser release];

    return xmlParser.dictionaryArray;
}

在这种情况下,xmlParser将在当前运行循环处理结束时发布,以便dictionaryArray在返回时有效。

第二种方式:

- (id)callRestService: (NSString *) methodName : (NSDictionary *) params
{
    NSURL *url=[self getRestUrl: methodName : params];
    XmlParser *xmlParser = [[XmlParser alloc] init];

    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    [parser setDelegate:xmlParser];
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    [parser parse];
    [parser setDelegate:nil];
    [parser release];
    [xmlParser.dictionaryArray autorelease]; // !!!
    [xmlParser release]; // !!!

    return xmlParser.dictionaryArray;
}

案例xmlParser将被解除分配为尽可能的。

(顺便说一下,别忘了发布parser