issue when trying to create my own cell

2019-08-23 22:22发布

问题:

I'm working on customizing my cell like below

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 static NSString *CellIdentifier = @"reusedCell";    
 DetailCell *cell = (DetailCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Customize the cell of each row from table
 if ( cell == nil ) {
     NSLog(@" MY CELL IS NIL");
     cell = [[DetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
else
     NSLog(@" MY CELL IS NOT NIL");
}

By debugging, I know that line 4-5 are not reached at all

MY CELL IS NOT NIL

Therefore, I cant create my own cell. According to apple documentation

Typically, the first thing the data source should do is send dequeueReusableCellWithIdentifier: to the table view, passing in a reuse-identifier string. If the table view does not return a reusable cell object, the data source creates one, assigning the object a reuse identifier in the final parameter of initWithStyle:reuseIdentifier:

Therefore, in my situation, the table view does return a reusable cell object... Where it comes from then... Have any one experienced this issue before. Please help thanks.

回答1:

The first time a list is shown, cell will always be nil. Then as cells are scrolled off the ends, they are recycled through the reusable list. So sometimes when you debug, the cell is nil, and sometimes you get a recycled cell. Also, if you use the same identifier (i.e. @"reusedCell") on multiple lists (which you shouldn't), a cell from another list may get recycled into your list. That's why you should keep the cell identifiers unique.



回答2:

If you want to create new cells each time when the user scrolls the table means, you need to override the reuseIdentifier property of the UITableViewCell in your custom cell class.

- (NSString *) reuseIdentifier
{
    return @"";
}

This will let you to create new cell. But, check out the memory usage. Bcoz you are creating new cell each time when the user scrolls the table.