This is probably a very simple question but I’m a little confused how this should be done right. I read that I need to remove this line of code:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
But then how do I check if the cell is not nil? The complete code I use is below. If someone could also please explain what the purpose this line:
static NSString *CellIdentifier = @"Cell";
Entire code:
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
You are using it right in the code you posted. The reason for having the static type modifier is to prevent the variable to be created and initialized each time the method is invoked. “Normal” variables are automatically created and deleted in each method, and you could in fact do this:
The
autotype modifier is default (compiler adds it) and to save typing people do not add it. By puttingstaticin front of the type you change this behavior so that the variable is initialized only once, when the program starts. It is calledstaticbecause the data in the variable with the type modifierstaticis not automatically removed from the stack each time the method is invoked…it is static/does not change. Hence the name.Since you are using the cell id over and over, it have a tiny performance benefit to initialize it only once instead of create/delete the variable each time the method is invoked. This could be especially true for tables with a lot of cells. However I have never seen the difference between using
autoandstaticvariables, but that is at least the idea behind it.You are not supposed to remove the
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];line. You need that to be able to dequeue table view cells from the tableview.