释放从参数创建的数组
如何释放从参数创建的数组?
我有类似的功能
-(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要了解对象所有权政策。
仅当方法名称包含
alloc
、new
或copy
时,您才会自动获得所有权。在这里,componentsSperatedByCharactersInSet:
没有。因此,返回的wordLiterals
不属于您。它是自动发布的。您不应该释放
它。当当前事件循环完成时自动释放池耗尽时,它会自动释放。如果您想保留该对象,则
保留
它。然后你就拥有它了。当您不再需要它时,您释放
它。You need to understand the Object Ownership Policy.
You only gain the ownership automatically when the method name contains
alloc
,new
orcopy
. Here,componentsSperatedByCharactersInSet:
does not. Therefore, the returnedwordLiterals
is not owned by you. It's autoreleased. You shouldn'trelease
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, yourelease
it.componentsSeparatedByCharactersInSet:...
返回的数组是自动释放的。几乎所有像这样创建的对象都是如此——即,不是通过alloc
或copy
创建的。如果您想保留它,您应该自己
保留
它。否则它会在未来某个未指定的时间消失(或者如果没有消失,则不是您的责任)。对不属于您的东西调用
release
将不可避免地导致失败,所以不要这样做。在这种情况下,由于您似乎仅在同一范围内使用它,因此您可以让它自行处理。The array returned by
componentsSeparatedByCharactersInSet:...
is autoreleased. This is true of pretty much all objects created like this -- ie, not viaalloc
orcopy
.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.