Objective-c – When to release a NSString in iPhone

cocoaiphoneobjective c

I have the following method

   -(NSMutableArray *) getPaises {
     NSMutableArray * paises;
     paises = [[NSMutableArray alloc] init];
     while( get new row ) {
      NSString *aPais =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
      [paises addObject:aPais];
     }
     return paises;
    }

I am not releasing the aPais, because if I do it the application crashes. I don't know when or if whether I should release it somewhere after using it and, if so, how do I do it. Just release the NSMutableArray is enough? Or do I have to traverse it and release each object?

And if I don't have to release it, who is the responsible for releasing?

Best Answer

As epatel said, you don't need to release that particular string. If you wanted to be more proactive, you could do this instead:

-(NSMutableArray *) getPaises {
    NSMutableArray * paises;
    paises = [[[NSMutableArray alloc] init] autorelease];
    while( get new row ) {
        NSString *aPais =  [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
        [paises addObject:aPais];
        [aPais release];
    }
    return paises;
}

In summary:

  • [[NSString alloc] initWith...] -> You must release or autorelease.

  • [NSString stringWith...] -> No need to release.

-- Edit: Added autorelease for paises, as you are returning it. When you return an object, always autorelease it if you have alloc&init'd it.