我应该如何正确释放这个 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
}
大家好,
如果我像上面那样释放 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
删除
[her_string release]
行,并将autorelease
添加到copy
中。问题是
copy
返回一个必须释放的字符串,并且通过使用substringFromIndex
调用覆盖该字符串,您会丢失对该字符串的引用。丢失引用后,它永远无法正确释放,因此字符串的第一个复制版本会泄漏(如果length > 0
,否则您的代码会正确释放该字符串)。substringFromIndex
返回一个已经自动释放的字符串,因此在您希望该字符串保留在当前自动释放池之外之前,您不必担心它。Remove the
[her_string release]
line, and addautorelease
to thecopy
.The issue is that the
copy
returns a string that must be released, and you lose the reference to it by overwriting the string withsubstringFromIndex
calls. After losing the reference it can never be properly released and thus the first copied version of the string leaks (iflength > 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.您不必释放 [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