NSData 类别中潜在的内存泄漏

发布于 2024-12-22 14:42:53 字数 480 浏览 5 评论 0原文

当使用 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 技术交流群。

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

发布评论

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

评论(2

俯瞰星空 2024-12-29 14:42:53

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.

方圜几里 2024-12-29 14:42:53

我猜你的应用程序崩溃是因为变量在使用之前被释放。如果您不立即使用返回值而是将其存储在成员变量中,建议调用retain

...
myMemberVariable = [something utf8String];
[myMemberVariable retain];
...

为了确保不会产生内存泄漏,您必须在某处释放成员变量。一个好的地方是dealloc

- (void)dealloc {
    if (myMemberVariable) [myMemberVariable release];

    [super 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.

...
myMemberVariable = [something utf8String];
[myMemberVariable retain];
...

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.

- (void)dealloc {
    if (myMemberVariable) [myMemberVariable release];

    [super dealloc];
}

I would also recommend having a look at Advanced Memory Management Programming Guide to get some detailed information about memory management of iOS.

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