Search code examples
objective-cobjectrelease-management

problems during object release


I have some problems during when and which object to be release

You can say my knowledge towards this is less

i have following conditions please suggest me the answer accordingly

  • situation-1

NSMutableString *str=[[NSMutableString alloc]initWithFormat:@"Hello World!"];
NSMutableArray *array=[[NSMutableArray alloc]init];
[array addObject:str];

Now when i tried to release str then usage of array affected in future...and Vice Versa
Tell me can i release both?

  • situation-2

NSMutableString *str=[[NSMutableString alloc]init]; str=@"Hello World !";
str=[self getData]; //calling a method which returns a string
[str release];

I think i am creating a memory leak here(how to solve it?)

please clear these situations


Solution

  • in the first situation, you'll need to call [str release]; after adding it to the array, like this:

    NSMutableString *str = [[NSMutableString alloc] initWithString:@"Hello World!"];
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:str];
    [str release];
    

    This way, array holds the only retain call on the string. Once you release array later, you won't have any memory leak issues.

    I'm a little confused about the second situation. str here is a pointer. You seem to be assigning three different objects to to same pointer:

    NSMutableString *str = [[NSMutableString alloc] init]; //first object
    str=@"Hello World !"; //second object
    str=[self getData]; //third object
    

    by the time you call [str release], you've created a memory leak because you've lost the first mutable string. The second time you called str =, you lost any way to access that first NSMutableString.

    Assuming that you're looking to concatenate all of these (since you chose NSMutableString), you might try this:

    NSMutableString *str = [[NSMutableString alloc] init]; //first object
    [str appendString:@"Hello World!"];
    [str appendString:[self getData]];
    [str release];
    

    If the [self getData] method returns an autoreleased string, you'll be fine. If getData returns a retained string (if you used alloc and init), you'll need to assign it to an intermediate pointer and release it after adding it to str.