Objective C, Memory leaking?
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict{
//currentElenet is NSString
currentElement = [elementName copy];
if ([elementName isEqualToString:@"struct"]) {
self.post = [[Question alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([currentElement isEqualToString:@"string"]) {
post.text = [NSString stringWithFormat:@"%@ %@", post.text, string];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"struct"]) {
[conversations addObject:post];
[post release];
post = nil;
}
}
//Question.m file
@synthesize text
-(id)init{
self = [super init];
if (self == nil) {
开发者_运维百科 }
else {
//declared as retain in .h file
text = [[NSString alloc]initWithString:@""];
}
return self;
}
-(void)dealloc{
[super dealloc];
[title release];
}
Do you guys see any memory leaking here? I call NSXML delegate methods and it basically put an instance of "Question" into NSMutableArray. I checked instrument and there is a memory leak while parsing it. But I don't see why...
currentElement = [elementName copy];
Please read the copy
API's description in the documentation. There it is mentioned that
this method retains the new object before returning it. The invoker of the method, however, is responsible for releasing the returned object.
You really need to include your property declarations in order for people to answer a memory management question with surety (since the properties define how the memory is managed), but assuming all retain
properties:
currentElement
never appears to be releasedtext
appears never to be releasedself.post
is assigned the result of[[Question alloc] init]
. The result of that method is already an object you own, and thepost
setter retains it again. It should be released before the method exits, along the lines of:id question = [[Question alloc] init]; self.post = question; [question release];
(It should also be released in
dealloc
or when you're done with it to balance the setter)
currentElement --- is not getting released in your parsing flow ... rest of the code looks correct
精彩评论