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

Memory management 如何处理子视图内存泄漏?,memory-management,memory-leaks,ios4,subview,Memory Management,Memory Leaks,Ios4,Subview,泄漏仪器正在对一些代码发出警报,但我不知道如何在不破坏应用程序的情况下解决泄漏问题。下面是一些代码,总结了我的方法,这些代码是不久前编写的,显然需要重新思考: labels = [[NSMutableArray alloc] init]; for(int i = 0; i < 10; i++) { // calculate x and y... label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 70, 15)]

泄漏仪器正在对一些代码发出警报,但我不知道如何在不破坏应用程序的情况下解决泄漏问题。下面是一些代码,总结了我的方法,这些代码是不久前编写的,显然需要重新思考:

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]];
}
我相信泄漏的发生是因为在正常的应用程序生命周期中,只有当superview在退出时被解除锁定时,标签才被解除锁定

救命啊


谢谢。

这可能是因为您没有释放标签数组。在for循环之后释放标签数组,然后使用.tag在UIView上设置标签,稍后使用.tag在setAlpha中使用viewWithTag来查找标签,怎么样

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];

我甚至比这种方法走得更远——决定不使用标签数组,只将标签添加为tag=100+I的子视图,然后在循环的每次迭代中释放它。
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];