Question

I have an array which loads in table view, and if users taps a certain cell it changes to UITableViewCellAccessoryCheckmark. How can I check what object in array is checked and add all objects that are checked to another array?

Was it helpful?

Solution

If you want a function that actually gets the checked objects at a whim, use the following:

- (NSMutableArray*)checkedObjectsInTable:(UITableView*)tableView
{
    NSMutableArray *checkedObjects = [[[NSMutableArray alloc] init] autorelease];
    for (int i=0; i<tableDataSource.count; i++)
        {
            if ([tableView cellForRowAtIndexPath:
                 [NSIndexPath indexPathForRow:i inSection:0]].accessoryType == UITableViewCellAccessoryCheckmark)
            {
                [checkedObjects addObject:[tableDataSource objectAtIndex:i]];
            }
        }

    return checkedObjects;
}

That would allow you to get the data on demand. Note that it would be much less efficient than simply using Jasarien's method, yet there are some situations where it is a better solution.

OTHER TIPS

Something like this in your tableView:didSelectRowAtIndexPath: method:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //set checkmark accessory on table cell ...

    // get object and add to checkedObjects array
    NSInteger index = [indexPath row];
    MyObject *object = [myArray objectAtIndex:index];
    [checkedObjects addObject:object];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top