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

发布于 2024-12-21 18:17:27 字数 457 浏览 5 评论 0原文

代码:

- (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
}

大家好,

如果我像上面那样释放 her_string,分析器会说这是调用者此时不拥有的对象的引用计数的错误递减

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

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

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

书间行客 2024-12-28 18:17:27

删除 [her_string release] 行,并将 autorelease 添加到 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...
    }
}

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

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

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.

逆蝶 2024-12-28 18:17:27

您不必释放 [NSString copy] 返回的 NSString
你只释放由 [[XXXX alloc] init] 创建的对象

IOS 5 使用 ARC,如果你使用 ARC,你永远不需要担心何时释放或保留

you don't have to release NSString returned by [NSString copy]
you only release object that is created by [[XXXX alloc] init]

IOS 5 use ARC, you never need to worried about when to release or retain if you work with ARC

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文