So I have the following code:
static NSString *CellIdentifier = @"RecommendationCell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TableViewCell"] autorelease];
}
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicator setCenter:CGPointMake(0, 15)];
[indicator startAnimating];
[indicator hidesWhenStopped];
UILabel *someLabel.........
UIView *containerView = [[UIView alloc] initWithFrame:CGRectZero];
[containerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
[containerView setAutoresizesSubviews:YES];
[containerView setBackgroundColor:[UIColor clearColor]];
[containerView addSubview:indicator];
[containerView addSubview:someLabel];
[containerView setFrameSize:CGSizeMake(indicator.frameWidth+self.loadingGeniusLabel_.frameWidth, 30)];
[containerView setCenter:CGPointMake(cell.contentView.center.x, 15)];
[cell.contentView addSubview:containerView];
[indicator release];
[containerView release];
return cell;
My question is, is the code above efficient/clean? The reason I ask is because if the cell that we get is from the reusable deck, then it would have the UIActivityIndicator and the necessary view in it right? Do I just have to add the subviews only if I am allocating a new cell (i.e: when the cell == nil)?
No
Yes, but since you are using the generic UITableViewCell, you won’t be able to access the UIActivityIndicator after adding it once. You’ll need to create a subclass of UITableViewCell to do this efficiently.
Yes
Only call addSubview outside of the if (cell == nil) block if you absolutely need to, it’s an expensive method call and will seriously impact your frames per second when scrolling the table.
Your best bet is subclassing UITableViewCell. That way, any objects/UIViews (or UIView subclasses) that you need to control the value/behavior of differently from cell to cell are better suited as properties on the UITableViewCell subclass. By doing this, you can instantiate them either in the xib file, or in the cell setup (inside that if statement), and then simply change the values for each cell (rather than creating the new objects each time).
Apple’s Table View Programming guide discusses this in depth:
http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html#//apple_ref/doc/uid/TP40007451
Apple’s sample project shows a couple different ways for managing table cells efficiently:
https://developer.apple.com/library/ios/#samplecode/TableViewSuite/Introduction/Intro.html