NSData 类别中潜在的内存泄漏
当使用 XCode 分析器时,我收到一条消息:
分配的对象的潜在泄漏
该代码位于我的 NSData(String)
类别中,代码是:
- (NSString*) utf8String
{
return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
}
现在我该如何解决这个问题?当我将语句更改为:
- (NSString*) utf8String
{
return [[[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding] autorelease];
}
我的应用程序在我调用 utf8String 的行崩溃。
When using the XCode analyzer I get a message saying:
Potential leak of an object allocated
The code this is in my NSData(String)
category, the code is:
- (NSString*) utf8String
{
return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
}
Now how can I solve this? When I change the statement to:
- (NSString*) utf8String
{
return [[[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding] autorelease];
}
My application crashes on the line where I call utf8String
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
cocoa 命名约定建议所有方法都返回自动释放的对象,但名称以“init”、“copy”或“new”开头的方法除外。静态分析器知道并检查这一点。
你有两个选择。你可以将该方法重命名为-newUTF8String,也可以返回一个autorelease对象,并在想要存储该方法的返回值时保留它。
我更喜欢后者,但两者都是有效的代码。
The cocoa naming conventions suggest that all methods return autoreleased objects, with the exception of methods whose names start with 'init', 'copy' or 'new'. The static analyzer knows and checks this.
You have two choices. You can rename the method to -newUTF8String, or you can return an autorelease object and retain it when you want to store the return value of this method.
I would prefer the latter, but both would be valid code.
我猜你的应用程序崩溃是因为变量在使用之前被释放。如果您不立即使用返回值而是将其存储在成员变量中,建议调用
retain
。为了确保不会产生内存泄漏,您必须在某处释放成员变量。一个好的地方是
dealloc
。我还建议您查看 高级内存管理编程指南,获取有关iOS内存管理的一些详细信息。
I guess your application crashes because the variable is released before it is used. It is recommended to call
retain
if you do not use the return value right away but store it in a member variable.To make sure that you do not produce a memory leak you have to release the member variable somewhere. A good place for that would be
dealloc
.I would also recommend having a look at Advanced Memory Management Programming Guide to get some detailed information about memory management of iOS.