ViewWithTag and addSubview

I am trying to reuse a shortcut by accessing the viewWithTag when I click on the UIButton. The code looks ok when it is executed the first time, but does it leak when you execute it multiple times due to line 7? Also is it better to remove the tag from supervisor, 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];

      

+3


source to share


2 answers


Move the code [self.view addSubview:label];

inside the block if

. When your if condition is false, it means the label is already part of the viewcontroller's view hierarchy, so if you add it again like in the original code, it will be saved twice.



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

      

+5


source


If you are using .xib or storyboard, just link it to the IBOutlet.



If you're only using code, try storing it as a private variable.

0


source







All Articles