I’m using DYRateView to display a star rating view in a custom UITableViewCell class. An instance of DYRateView (subclass of UIView) is allocated and initialized in my `layoutSubviews’ method.
Is it a bad practice to alloc/init the view in `layoutSubviews’? When the cell is reused, does it alloc/init in every cell or reuse the view?
.h
@property (retain, nonatomic) IBOutlet DYRateView *rateView;
.m
- (void)layoutSubviews
{
[super layoutSubviews];
rateView = [[DYRateView alloc] initWithFrame:CGRectMake(100, 60, 160, 20) fullStar:[UIImage imageNamed:@"StarFullLarge.png"] emptyStar:[UIImage imageNamed:@"StarEmptyLarge.png"]];
NSLog(@"created");
rateView.padding = 10;
rateView.alignment = RateViewAlignmentCenter;
rateView.editable = YES;
rateView.delegate = self;
rateView.rate = _rating;
[self.contentView addSubview:rateView];
}
It is ok to allocate it in
layoutSubviews, however you are doing it every timelayoutSubviewsis called, and it will be called more frequently than just after an allocation. So, the way you have it now will leak memory badly (unless you are using ARC). Furthermore, you will be constantly adding newrateViewobjects to yourcontentViewon every invocation, with rather undesirable consequences.Since the subview is owned by the cell view, if the cell view is reused, it too will be reused.
Instead, check if the subview exists or not, and allocate accordingly.