Search code examples
iosuitableviewcheckmark

iOS - how to set a checkmark in a UITableView the first time the table is loaded


I am an iOS newbie. I am using a checkmark to in a UITableView, and storing the checked value in a local database. When I load the app for the first time, I want to set the value of the checkmark depending on which value exists in the db. How would I do that? Presently this is what I do -

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if ([indexPath compare:self.lastIndexPath] == NSOrderedSame) 
{
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
} 
else 
{
    cell.accessoryType = UITableViewCellAccessoryNone;
}
// Set up the cell...
NSString *cellValue = [[self countryNames] objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;

return cell;
}

and then in didSelectRowAtIndexPath -

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

// some stuff
self.lastIndexPath = indexPath;
[tableView reloadData];
}

Solution

  • Are you asking simply how and when to set the checkmark or are you asking how to populate a table from a database (eg Core Data)?

    From your code, the only data you represent is in [self countryNames] and it's not clear under what circumstances you'd want the cell to display a checkmark. Whatever that is, just check the condition and set the checkmark when you are configuring your cell for data (after your "Set up the cell..." comment).

    Example if you stored the users country and checked that cell:

    // get the current country name
    NSString *cellValue = [[self countryNames] objectAtIndex:indexPath.row];
    
    // configure the cell
    cell.textLLabel.text = cellValue;
    UITableViewCellAccessoryType accessory = UITableViewCellAccessoryNone;
    if ([cellValue isEqualToString:self.usersCountry]) {
        accessory = UITableViewCellAccessoryCheckmark;
    }
    cell.accessoryType = accessory;