2017-08-14 45 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"); 
} 
相關問題