问题
I am trying to reuse the label by making a call to viewWithTag when I press the UIButton. The code looks ok when it is executed the first time, but is it leaking on executing it multiple times due to line 7? Also is it just better to remove the label from the superview, alloc and addSubview instead of using 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];
回答1:
Move the code [self.view addSubview:label];
inside your if
block. When your if condition is false, that means the label is already part of of your viewcontroller's view hierarchy, so if you add it again like in your original code it will be double retained.
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];
}
回答2:
If you are using a .xib or storyboard just link it with an IBOutlet.
If you'r using code only, try to save it as a private variable.
来源:https://stackoverflow.com/questions/9691865/viewwithtag-and-addsubview