如何处理子视图内存泄漏?

发布于 2024-10-06 09:04:33 字数 631 浏览 2 评论 0原文

泄漏工具正在对某些代码发出警报,但我不知道如何在不导致应用程序崩溃的情况下解决泄漏问题。这里有一些代码总结了我的方法,这些代码是前一段时间写的,显然需要重新思考:

labels = [[NSMutableArray alloc] init];

for(int i = 0; i < 10; i++) {
    // calculate x and y...
    label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 70, 15)];
    // customize label...
    [labels addObject:label];
    [label release];
    [self addSubview:[labels objectAtIndex:i]];
}

为什么要费心使用标签 NSMutableArray?后来,在其他方法中,我需要更改标签的 alpha,并且可以很方便地说

[[labels objectAtIndex:num] setAlpha:0.5];

我相信发生泄漏,因为标签在正常应用程序生命周期期间不会被释放,只有当超级视图被释放时就退出了。

帮助!

谢谢。

The Leaks instrument is sounding the alarm on some code, but I don't know how to address the leak without crashing the app. Here's some code summarizing my approach, written some time ago and clearly in need of rethinking:

labels = [[NSMutableArray alloc] init];

for(int i = 0; i < 10; i++) {
    // calculate x and y...
    label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 70, 15)];
    // customize label...
    [labels addObject:label];
    [label release];
    [self addSubview:[labels objectAtIndex:i]];
}

Why bother with the labels NSMutableArray? Later, in other methods, I need to change the alpha of the labels, and it's convenient to be able to say

[[labels objectAtIndex:num] setAlpha:0.5];

I believe the leak occurs because labels doesn't get dealloc'ed during the normal app lifecycle, only when the superview is dealloc'd at quit.

Help!

Thanks.

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

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

发布评论

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

评论(1

木槿暧夏七纪年 2024-10-13 09:04:33

发生这种情况可能是因为您没有释放标签数组。在 for 循环之后释放标签数组,然后使用 .tag 在 UIView 上设置标签,并稍后使用 viewWithTag 来 setAlpha 通过 .tag 找到标签怎么样?

labels = [[NSMutableArray alloc] init];

for(int i = 0; i < 10; i++) {
    // calculate x and y...
    label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 70, 15)];
    label.tag = 100;
    // customize label...
    [labels addObject:label];
    [label release];
    [self addSubview:[labels objectAtIndex:i]];
}

[labels removeAllObjects];
[labels release];

然后后来

(UILabel*) [[self.view viewWithTag:100] setAlpha:0.5];

It's probably happening because you're not dealloc'ing the labels array. What about releasing the labels array after the for loop, then using .tag to set the label on the UIView and find the label later via the .tag using viewWithTag to setAlpha?

labels = [[NSMutableArray alloc] init];

for(int i = 0; i < 10; i++) {
    // calculate x and y...
    label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 70, 15)];
    label.tag = 100;
    // customize label...
    [labels addObject:label];
    [label release];
    [self addSubview:[labels objectAtIndex:i]];
}

[labels removeAllObjects];
[labels release];

Then later

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