Reputation: 127713
Let us look some standard codes of tableview
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
static int count = 0;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
NSLog(@"count %d", count++);
}
// Configure the cell...
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
If we have 10 items in array, then it will alloc 10 cells for each indexPath.row
My question is how does the function reuseIdentifier:CellIdentifier know different row ?
Upvotes: 1
Views: 1630
Reputation: 3250
Oh, the method **dequeueReusableCellWithIdentifier**:
has nothing to do with indexPath.
When using UITableView, we use [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault] reuseIdentifier:cellIdentifier]
to put the cell of a very kind into the cache (maybe an NSMutableDictionary) with key 'cellIdentifier'. And then, when we need one more cell, we query the cache first, if missed, we create a new one.
The indexPath is the coder's responsibility to treat. You separate different kinds of cells by sections, and show cells row by row in one section. Section and Row make up an NSIndexPath.
Upvotes: -1
Reputation: 170829
If we have 10 items in array, then it will alloc 10 cells for each indexPath.row
That's not true - normally number of allocated cells will be NumberOfVisibleRows+2 (or similar value).
This is (roughly) how UITableView works: Once certain cell is scrolled out of visible area it is removed from UITableView view hierarchy (set table's clipToBounds property to NO and you'll be able to see that!) and is put to a some kind of internal cache. dequeueReusableCellWithIdentifier:
method checks if there's cell available for reuse in that cache and returns it (and returns nil if no cell is available) - so you don't need to allocate cells more then actually fit visible area.
dequeueReusableCellWithIdentifier
method does not depend on current indexPath, rather on cell string identifier you pass to it. And indexPath is used only by you to get appropriate contents to a cell.
Upvotes: 3