我应该如何正确释放这个NSString?

Sky*_*ler 2 memory-management objective-c release-management nsstring

码:

- (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
}
Run Code Online (Sandbox Code Playgroud)

大家好,

如果我her_string像上面那样发布,分析师说it's an incorrect decrement of the reference count of an object that is not owned at this point by the caller.

否则,如果我不释放它,它说这是一个潜在的内存泄漏.

我应该在哪里以及如何发布它?谢谢!

Mic*_*kel 10

删除该[her_string release]行,然后添加autoreleasecopy.

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

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

问题是copy返回一个必须释放的字符串,并且通过使用substringFromIndex调用覆盖字符串而丢失对它的引用.丢失引用后,它永远不会被正确释放,因此字符串的第一个复制版本泄漏(如果length > 0,否则您的代码正确释放字符串).

substringFromIndex 返回一个已经自动释放的字符串,因此在您希望字符串在当前自动释放池之外保留​​之前,您不必担心它.