如何在下面的函数中安全地释放变量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;
}
答案 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
)