Generating UILabel inside a UIView / Memory leak

Hi together,


I have a custon view class which inherits from UIView. Inside the

- (void)drawRect:(CGRect)rect {}


I also generate some UILabels via

UILabel* aLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, length, height)];
[self insertSubview:aLabel atIndex:1];
[self.labelArray addObject:aLabel];


I put this view into an array container to remove all labels when drawRect is called again (last line)

At the beginning of my drawRect I remove all labels via


    for (int i = 0; i < [self.labelArray count]; i++) {
        [[self.labelArray objectAtIndex:i] removeFromSuperview];
    }


This iseems not to work because the memory usage increases during runtime.


How to remove the labels without leaking memory? Is there a better way to solve this issue?

Replies

Are you also removing the labels from your array? ([self.labelArray removeAllObjects])


I don't think that's a good approach adding subviews in drawRect though. I would think creating and adding new subviews will almost certainly trigger another drawRect call. Perhaps you could find another better place to add your subviews - maybe in layoutSubviews (with some sort of flag to prevent infinite recursion) or better yet, in some other method that is only called by whatever is triggering the content update.

Hi junkpile,


thanks for you help. I'll look for a new approach. Thanks.


Walter

Memory usage is increaing because you are implementing -drawRect:, which means that we have to allocate a backing store for your view.


The only thing you should do inside of -drawRect: is draw. If you have no reason to draw, do not implement -drawRect: (even an empty implementation).


If you want to add or remove subviews at the last possible moment, use -layoutSubviews to do so instead. If you also have auto layout constraints to add, you may consider doing all of this inside of -updateConstraints. But -drawRect: is not the correct place for this.