解决了没有互联网和使用initWithContentsOfURL时touchXML泄漏的问题

时间:2011-12-08 12:04:19

标签: iphone objective-c cocoa-touch xml-parsing

每次都会在仪器中显示泄漏的CXMLDocument对象,向Web服务发出XML请求以及没有可用的Internet连接时。这是我的代码:

NSString *path = ... some URL
NSURL *url = [NSURL URLWithString: path];
CXMLDocument *itemListParser; = [[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil];
... other stuff ...

如果我们深入挖掘并跟踪initWithContentsOfURL调用,那么我们将在“CXMLDocument.m”中找到此方法:

- (id)initWithContentsOfURL:(NSURL *)inURL encoding:(NSStringEncoding)encoding options:(NSUInteger)inOptions error:(NSError **)outError
  {
  if (outError)
    *outError = NULL;

  NSData *theData = [NSData dataWithContentsOfURL:inURL options:NSUncachedRead error:outError];
  if (theData)
    {
    self = [self initWithData:theData encoding:encoding options:inOptions error:outError];
    }
  else
    {
        [self release]; //My suggested fix: We need to release an alloc'ed object because after the "self = null" it will be unable to release it. See the info below.
        self = NULL;
    }

  return(self);
}

看来,如果Data为nil(例如没有连接)则self将为nil,因此调用TouchXML initWithContentsOfURL的结果也将为零。所以,在我的代码中:

CXMLDocument *itemListParser; = [[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil];

我正在分配内存,但init返回nil,因此itemListParser也变为nil。所以稍后,尝试使用[itemListParser release]释放解析器什么都不做,因为release被发送到nil。

我能够通过在“self = NULL”之前添加“[self release]”来修复泄漏(请参阅TouchXML initWithContentsOfURL方法中的注释行)

0 个答案:

没有答案
相关问题