casillas
casillas

Reputation: 16793

indexPath comparison in TableView

I am storing selected indexPath inside a mutabledictionary `selectedRowsInSectionDictionary as follows.

For example in the following dictionary it shows, first section which is key. And in this section, first (1,0), second(1,1) and third(1,2) rows has been chosen and stored inside the dictionary.

enter image description here

I am trying to check whether or not these indexPath is stored inside the dictionary in the cellForRowAtIndexPath delegate method, but it always returns false. i am wondering what I am doing wrong?

if([selectedRowsInSectionDictionary objectForKey:@(indexPath.section)] == indexPath)
{
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

Upvotes: 1

Views: 586

Answers (2)

Paulw11
Paulw11

Reputation: 114783

[selectedRowsInSectionDictionary objectForKey:@(indexPath.section)] is an NSMutableArray reference, not an indexPath, so the comparison will never be true.

I would suggest that you store NSMutableIndexSet in your dictionary, rather than an array. Your code would then be something like:

NSMutableIndexSet *selectedSet = selectedRowsInSectionDictionary[@(indexPath.section)];
if ([selectedSet containsIndex:indexPath.row] {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
    cell.accessoryType = UITableViewCellAccessoryNone;
}

To add/remove items to the dictionary using a 'toggle' you would use:

NSMutableIndexSet *selectedSet = selectedRowsInSectionDictionary[@(indexPath.section)];

if (selectedSet == nil) {
    selectedSet = [NSMutableIndexSet new];
    selectedRowsInSectionDictionary[@(indexPath.section)] = selectedSet;
}

if ([selectedSet containsIndex:indexPath.row]) {
    [selectedSet remove:indexPath.row];
} else {
    [selectedSet add:indexPath.row];
}

Upvotes: 3

Lachlan
Lachlan

Reputation: 312

This is failing as the value of the dictionary is an array.

As far as I can tell

[selectedRowsInSectionDictionary objectForKey:@(indexPath.section)]

Will return an array containing 3 elements (The NSIndexPaths). You should be able to modify your code to the following:

if([[selectedRowsInSectionDictionary objectForKey:@(indexPath.section)] containsObject:indexPath]
{
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

I have confirmed this with the following testing code:

NSIndexPath *comparisonIndexPath = [NSIndexPath indexPathForRow:2 inSection:0];
NSDictionary *test = @{ @(1): @[[NSIndexPath indexPathForRow:1 inSection:0],
                                comparisonIndexPath,
                                [NSIndexPath indexPathForRow:3 inSection:0]]};
NSArray *indexPathArray = [test objectForKey:@(1)];
if ([indexPathArray containsObject:comparisonIndexPath]) {
    NSLog(@"Yeeehawww, let's do some stuff");
}

Upvotes: 1

Related Questions