@property (strong,nonatomic)NSMutableSet*selectedRows;
@property(nonatomic,retain) IBOutlet UITableView *tableView;
...說明需要(UITableView的,的NSMutableSet)
self.selectedRows = [NSMutableSet new];
...
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.selectedRows containsObject:indexPath]){
[self.selectedRows removeObject:indexPath];
}else{
[self.selectedRows removeAllObjects];//test 1 item only
[self.selectedRows addObject:indexPath];
}
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"heightForRowAtIndexPath %@ \nSelected %@", indexPath,self.selectedRows);
for (NSIndexPath*item in self.selectedRows) {
if ([item compare:indexPath]==NSOrderedSame) {
NSLog(@"EXIST1");
}
if (item.section == indexPath.section && item.row == indexPath.row) {
NSLog(@"EXIST2");
}
}
if ([self.selectedRows containsObject:indexPath] == YES) {
NSLog(@"EXIST3");
}
return 44.0f;
}
重繪細胞後我期望過濾器選擇的小區。
的問題是,爲什麼我只得到這個日誌: EXIST1 EXIST2
哪裏是EXIST3?
簡單的測試:
NSMutableSet*s =[NSMutableSet new];
NSIndexPath*p1 = [NSIndexPath indexPathForRow:1 inSection:1];
NSIndexPath*p2 = [NSIndexPath indexPathForRow:1 inSection:1];
NSComparisonResult r1= [p1 compare:p2];
NSLog(@"p1 compare p2 = %@", [email protected]"YES":@"NO");
[s addObject:p1];
NSLog(@"contain p1 =%@", [s containsObject:p1][email protected]"YES":@"NO");
NSLog(@"contain p2 =%@", [s containsObject:p2][email protected]"YES":@"NO");
NSLog(@"s = %@",s);
結果
2014-01-08 04:42:57.477 test[28342:70b] p1 compare p2 = YES
2014-01-08 04:42:57.478 test[28342:70b] contain p1 =YES
2014-01-08 04:42:57.478 test[28342:70b] contain p2 =YES
2014-01-08 04:42:57.479 test[28342:70b] s = {(
<NSIndexPath: 0x8b2e0d0> {length = 2, path = 1 - 1}
)}
我覺得-containsObject之間的差異,-compare是-containsObject:長得一模一樣的對象和-compare比較對象的內容。因爲在你的情況下,對象的內容是相同的,但不是對象本身。 – Sitses
在這種情況下在測試中[s containsObject:p2]應該返回NO –
不,因爲在你的測試用例中,編譯器會優化你的代碼並將p1和p2設置爲同一個對象,因爲它們都是用相同的值靜態分配的。 – Sitses