2017-08-14 97 views
1

我将选定的indexPath存储在可变字典`selectedRowsInSectionDictionary中,如下所示。TableView中的indexPath比较

例如在下面的字典中显示,第一部分是关键。在本节中,首先(1,0),第二(1,1)和第三(1,2)行已被选择并存储在字典中。

enter image description here

我想检查这些indexPath是否被存储在cellForRowAtIndexPath委托方法的字典里面,但它始终返回false。我想知道我做错了什么?

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

尝试isEqual:方法方法在您的比较条件在更换==的。还要确保从字典返回的对象实际上是一个NSIndexPath对象。 – Bamsworld

+0

可能重复[如何比较两个NSIndexPaths?](https://stackoverflow.com/questions/6379101/how-to-compare-two-nsindexpaths) –

+0

@ShamasS,其实我的问题是sligthly不同,我有一个数组要检查的indexPathes。 – hotspring

回答

3

[selectedRowsInSectionDictionary objectForKey:@(indexPath.section)]NSMutableArray参考,而不是indexPath,这样比较永远不会为真。我建议你在你的字典中存储NSMutableIndexSet而不是数组。然后,您的代码将是这样的:

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

要添加/删除项目使用“切换”词典中,你可以使用:

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]; 
} 
+0

它显示以下错误'NSMutableIndexSet'没有可见的接口有'contains'方法。 – hotspring

+0

对不起,Swift和Objective-C方法名称是有区别的。我已经更新了它 – Paulw11

+0

你有什么想法的相关问题https://stackoverflow.com/questions/48483622/reload-section-does-not-handle-properly – hotspring

2

这失败作为字典的值是一个阵列。

据我可以告诉

[selectedRowsInSectionDictionary objectForKey:@(indexPath.section)] 

将返回包含3个元素(该NSIndexPaths)的阵列。 您应该可以修改代码以下列:

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

我曾与下面的测试代码证实了这一点:

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"); 
}