泄漏XMLParser的问题

时间:2010-08-02 05:14:15

标签: iphone memory-leaks nsxmlparser

我一直在努力让xml解析器无泄漏且高效,但到目前为止还没有成功。我删除了其他字段,因为它们都是一样的。

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    currentElement = [[elementName copy] autorelease];
    if ([elementName isEqualToString:@"source"]) {
        if (!currentID) {
            overlays = [[NSMutableArray alloc] init];
            currentID = [[NSMutableString alloc] init];
        } else {
            [currentID release];
            currentID = nil;
            currentID = [[NSMutableString alloc] init];
        }
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    if ([elementName isEqualToString:@"source"]) {
         overlay = [[NSMutableDictionary alloc] init];
         [overlay setObject:currentID forKey:@"id"];
        [overlays insertObject:overlay atIndex:[overlays count]];
        [overlay release];
        overlay = nil;
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
   string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
   string = [string stringByReplacingOccurrencesOfString:@"\t" withString:@""];
   if ([currentElement isEqualToString:@"id"]) {
        [self.currentID appendString:string];
   }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
    [currentID release];
    currentID = nil;
    //[self addResources];
 }

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果您已声明ivars的属性,我建议您使用它们。这使内存管理更容易。这就是我编写代码的方式:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    self.currentElement = elementName;
    if ([elementName isEqualToString:@"source"]) {
        if (!self.currentID) {
            self.overlays = [NSMutableArray array];
            self.currentID = [NSMutableString string];
        } else {
            self.currentID = [NSMutableString string];
        }
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    if ([elementName isEqualToString:@"source"]) {
        [self.overlays addObject:
        [NSDictionary dictionaryWithObjectsAndKeys:self.currentID,@"id",nil]];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
   string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
   string = [string stringByReplacingOccurrencesOfString:@"\t" withString:@""];
   if ([self.currentElement isEqualToString:@"id"]) {
        [self.currentID appendString:string];
   }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
    self.currentID = nil;
}

您可能还想尝试使用Build& Analyze代码。这可能会指出你在哪里泄漏。