Search code examples
objective-creleaseretain

Retain and release nsstring


str is a NSString I own. It is my responsibility to release it, since I call initWithString:

if (![[str substringFromIndex:str.length-1] isEqualToString:@"\n"])
{
    str = [str stringByAppendingString:@"\n"];
}

if the line inside the if statement reached, I will lose the ownership of the str var.

so my app crashes with a zombie instance, when I release str later:

[str release];

All goes fine if the if statement is NO(false).

What can I do to maintain the ownership of str?

Note that str could be very long I don't want to init another NSString


Solution

  • You need to do normal memory management:

    if (![[str substringFromIndex:str.length-1] isEqualToString:@"\n"])
    {
        NSString *newStr = [str stringByAppendingString:@"\n"];
        [str release];
        str = [newStr retain];
    }
    

    Keep in mind that stringByAppendingString: returns an autoreleased string (and it also creates a whole new string).