如何处理子视图内存泄漏?
泄漏工具正在对某些代码发出警报,但我不知道如何在不导致应用程序崩溃的情况下解决泄漏问题。这里有一些代码总结了我的方法,这些代码是前一段时间写的,显然需要重新思考:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况可能是因为您没有释放标签数组。在 for 循环之后释放标签数组,然后使用 .tag 在 UIView 上设置标签,并稍后使用 viewWithTag 来 setAlpha 通过 .tag 找到标签怎么样?
然后后来
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?
Then later