Dequeuing reusable cells from UITableView
Why this code works fine:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.text = [NSString stringWithFormat:@"cell%i%i", indexPath.section, indexPath.row];
}
return cell;
}
As far as I understood cell identifiers, this code should work correctly only if I move cell.textLabel.text = ...
line out of if-statement. In other words, why labels have cor开发者_如何学编程rect texts???
Try creating more cells than you can see on your screen and as soon as they get dequeued they will no longer have the text you expect...
It will basically be okay for 5 or so rows you see on the screen but as soon as you start scrolling you'll be seeing some "interesting" stuff :)
The created cell gets reused. This means that the object is marked for being reused (and thus saving you the complete creation of the object).
So once it scrolls out of the screen a cell is marked as reusable. Because of this, you first check if there are any reusable cells ([tableView dequeueReusableCellWithIdentifier:), before you create a new one.
The text you need to set, since it's (probably) different for every cell of your table, but has nothing to do with object creation/destruction.
精彩评论