why do we use dequeueReusableCellWithIdentifier if the cells and section fill exactly the size of the screen, or even less than the height of the screen : let’s say we have 2 sections with only 1 row for each?
example :
switch (indexPath.section)
{
case kMonitoringSection:
{
cell = [tableView dequeueReusableCellWithIdentifier:kMonitoringCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kMonitoringCellIdentifier] autorelease];
cell.textLabel.text = NSLocalizedString(@"Monitoring", @"");
UISwitch *switchCtl = [[[UISwitch alloc] initWithFrame:CGRectMake(197, 8, 94, 27)] autorelease];
[switchCtl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
switchCtl.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:switchCtl];
}
break;
}
case kLevelSection:
{
cell = [tableView dequeueReusableCellWithIdentifier:kLevelCellIdentifier];
UILabel *levelLabel = nil;
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kLevelCellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text = NSLocalizedString(@"Level", @"");
levelLabel = [[[UILabel alloc] initWithFrame:CGRectMake(171, 11, 120, 21)] autorelease];
levelLabel.tag = kLevelTag;
levelLabel.textAlignment = UITextAlignmentRight;
[cell.contentView addSubview:levelLabel];
levelLabel.backgroundColor = [UIColor clearColor];
}
in the sample code : BatteryStatus
if we had 20 rows, i would understand the point, but i’m not sure here…
Thanks
If you only have a static number of cells, say only two (different) cells in your tableView and no cell is repeated, you should instead instanciate your two cells in your XIB (and design them there with your
UISwitchfor the first one and your customUILabelfor the other) and point an IBOutlet to it.Much simpler, less code, and totally makes sense when no reuse of the cells is needed.
Do read Apple’s Table View Programming Guide which is a really great resource (like quite every Programming Guide in Apple’s doc) and explains all this in details. In particular the part “The Technique for Static Row Content“ explains this exact use case.
So of course you can use
dequeueReusableCellWithIdentifierin such case, it won’t hurt (and probably in the BatteryStatus sample they did it because they didn’t wonder if it was really useful or not, just as an habit because they do this all the time when they have more rows), but it is not the best way to do it.Note that sample codes provided by Apple are not always the solution to follow: they are just one way to do sthg, and especially the sample generally tend to focus on the fonctionnality it wants to test (in this case the Battery Status) and does not worry about anything else (especially performance — except if the sample is about performance of course).