codereviewanskquestions
codereviewanskquestions

Reputation: 13998

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...

Upvotes: 0

Views: 102

Answers (3)

Chuck
Chuck

Reputation: 237030

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 released

  • text appears never to be released

  • self.post is assigned the result of [[Question alloc] init]. The result of that method is already an object you own, and the post 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)

Upvotes: 1

Girish Kolari
Girish Kolari

Reputation: 2515

currentElement --- is not getting released in your parsing flow ... rest of the code looks correct

Upvotes: 0

YPK
YPK

Reputation: 1851

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.

Upvotes: 2

Related Questions