I was wondering about good and memory efficient ways to reload all the changes made to an UITableView. Imagine the native Note Apps of Apple which refreshes the UITableView if you’ve changed the date/title of a note.
When I animate the index into view which shows you the contents, I make sure to reload my index data like so
[indexTable reloadData];
Now the only problem is that not every cell will be refreshed if it was used before, because I had this in my function which loads the cells:
//if (cell == nil) { // assign a label to them, e.g. the title of a note
//} else {
// label = (UILabel *) [cell viewWithTag:1];
//}
See below for the entire code. I am now actually wondering that the label = (UILabel *) [cell viewWithTag:1]; bit does? All I know is that it doesn’t refresh my data if the user has entered a new note title for instance (despite me calling indexTable reload!).
Will I run into serious problems by leaving it out as I do in the following code?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UILabel *label;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//NSLog(@"checking if cell is nil");
//if (cell == nil) {
NSLog(@"cell=nil");
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
CGRect frame = CGRectMake(10, 0, 200, 30);
label = [[UILabel alloc] initWithFrame:frame];
label.lineBreakMode = UILineBreakModeTailTruncation;
label.tag = 1;
label.text = [[indexContent objectAtIndex:indexPath.row] itemTitle];
[cell.contentView addSubview:label];
[label release];
//} else {
// label = (UILabel *) [cell viewWithTag:1];
//}
return cell;
}
Any explanations would be very much appreciated!
You should check for the result of
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];to benil, although not doing so, won’t make your app crashing, you will init/alloc a new cell each time this method is called, and it’s better to try to reuse a cell (why trying to resue the cell, if you alloc/init a new one each time ?).label = (UILabel *) [cell viewWithTag:1];doesn’t make any refresh for sure, it just retrieve aUILabel, which is a subview of the cell, given a tag. In the if part, you alloc/init a new cell because it is required and configure itsframe,lineBreakMode, andtagproperties and add it to the cell.So in order for your content to refresh (using
[tableView reloadData];), extract theUILabelcontent setting part outside the if/else sequence, and cut off the else part :