Search code examples
objective-cmemory-managementnsstringrelease-management

how should I release this NSString correctly?


Code:

- (void) foo : (NSString*) ori_string
{
    her_string = [ori_string copy];

    while ([her_string length]>0) 
    {
        her_string = [her_string substringFromIndex:1];
        //do something...
    }

    [her_string release];  //Here is the problem
}

Hi all,

if I release her_string like above, the Analyzer said that it's an incorrect decrement of the reference count of an object that is not owned at this point by the caller.

Otherwise if I don't release it, it said that it's a potential memory leak.

Where and How should I release it? Thank you!


Solution

  • Remove the [her_string release] line, and add autorelease to the copy.

    - (void) foo : (NSString*) ori_string
    {
        her_string = [[ori_string copy] autorelease];
    
        while ([her_string length]>0) 
        {
            her_string = [her_string substringFromIndex:1];
            //do something...
        }
    }
    

    The issue is that the copy returns a string that must be released, and you lose the reference to it by overwriting the string with substringFromIndex calls. After losing the reference it can never be properly released and thus the first copied version of the string leaks (if length > 0, otherwise your code properly releases the string).

    substringFromIndex returns an already-autoreleased string, so you don't have to worry about it until you want the string to persist outside of the current autorelease pool.