viewWithTag和addSubview

当我按下UIButton时,我试图通过调用viewWithTag来重用标签。 第一次执行代码时代码看起来没问题,但是由于第7行,代码执行多次就会泄漏? 还有更好的方法是从superview,alloc和addSubview中删除标签而不是使用viewWithTag吗?

1. UILabel *label = (UILabel *)[self.view viewWithTag:100]; 2. if(label == nil) { 3. label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)] autorelease]; 4. label.tag = 100; 5. } 6. 7. [self.view addSubview:label]; 

移动代码[self.view addSubview:label]; 在你的if块内。 当if条件为false时,这意味着标签已经是viewcontroller视图层次结构的一部分,因此如果您再次添加它,就像在原始代码中一样,它将被双重保留。

 UILabel *label = (UILabel *)[self.view viewWithTag:100]; if (!label) { label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)] autorelease]; label.tag = 100; [self.view addSubview:label]; } 

如果您使用的是.xib或故事板,只需将其与IBOutlet链接即可。

如果您仅使用代码,请尝试将其另存为私有变量。