释放从参数创建的数组

发布于 2024-09-04 02:19:19 字数 336 浏览 2 评论 0原文

如何释放从参数创建的数组?

我有类似的功能

-(NSMutableArray*)composePhrase:(NSString*) phraseLiteral{
   ...
   NSArray* wordLiterals=[phraseLiteral componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"]];
   ...
   [wordLiterals release];
}

,但我总是遇到这个版本的问题。谁能告诉我如何做对吗?

How can I release an array created from a parameter?

I have function like

-(NSMutableArray*)composePhrase:(NSString*) phraseLiteral{
   ...
   NSArray* wordLiterals=[phraseLiteral componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"]];
   ...
   [wordLiterals release];
}

and I always got problem with this release. Can anyone tell me how to make it right?

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

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

发布评论

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

评论(2

三月梨花 2024-09-11 02:19:19

您需要了解对象所有权政策。

仅当方法名称包含 allocnewcopy 时,您才会自动获得所有权。在这里,componentsSperatedByCharactersInSet: 没有。因此,返回的 wordLiterals 不属于您。它是自动发布的。您不应该释放它。当当前事件循环完成时自动释放池耗尽时,它会自动释放。

如果您想保留该对象,则保留它。然后你就拥有它了。当您不再需要它时,您释放它。

You need to understand the Object Ownership Policy.

You only gain the ownership automatically when the method name contains alloc, new or copy. Here, componentsSperatedByCharactersInSet: does not. Therefore, the returned wordLiterals is not owned by you. It's autoreleased. You shouldn't release it. It's released automatically when the autorelease pool is drained when the current event loop is complete.

If you want to keep the object, you retain it. Then you own it. When you no longer needs it, you release it.

情痴 2024-09-11 02:19:19

componentsSeparatedByCharactersInSet:... 返回的数组是自动释放的。几乎所有像这样创建的对象都是如此——即,不是通过alloccopy创建的。

如果您想保留它,您应该自己保留它。否则它会在未来某个未指定的时间消失(或者如果没有消失,则不是您的责任)。

对不属于您的东西调用release将不可避免地导致失败,所以不要这样做。在这种情况下,由于您似乎仅在同一范围内使用它,因此您可以让它自行处理。

The array returned by componentsSeparatedByCharactersInSet:... is autoreleased. This is true of pretty much all objects created like this -- ie, not via alloc or copy.

You are expected to retain it yourself if you want to keep hold of it. Otherwise it will evaporate at some unspecified future time (or if it doesn't it's not your responsibility).

Calling release on something you don't own will inevitably lead to grief down the line, so don't do it. In this case, since you seem to be using it only within the same scope, you can just let it take care of itself.

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