我不确定你真正的问题,以及你想在这里实现的目标......但我会像这样改进你的 code-sn-p:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString*nameForItem = [NSString stringWithFormat:@"%@", [self.ivc.objects objectAtIndex:indexPath.row]];
Items *item = [Items new];
[item setNameOfItem:nameForItem];
[item setNumberOfItem:[NSNumber numberWithInt:1]];
// improving comparison
if (indexPath.row == self.index.row && indexPath.section == self.index.section) {
[item setNumberOfItem:[NSNumber numberWithInt:[item.numberOfItem integerValue]+1]];
}
// removing unnecessary instantiate and deep-copying the current index path
self.index = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
}
问题 #1
当你比较实际的指针时:
if (indexPath == self.index) { ... }
您需要知道NSIndexSet 的相同 实例可以保存不同的row 和section 值(根据我的评论),因为它们被@987654326 重用(!) @,所以你可能想比较实际的索引而不是指针。
问题 #2
同时保留索引路径的指针,例如:
self.index = indexPath;
您需要注意我在上面一段中提到的完全相同的事情,关于 NSIndexPath 的同一个实例可以并且将被重用来呈现新的索引。
更新
如果您希望为每个索引路径处理一个计数器(=UITableView 的当前实例中的行),您需要将这些数字永久存储在某个集合中的某个位置。
我不确定当前的环境,所以我试图为这个问题提供一个通用的解决方案。
在您的课堂上,您将需要这个(私人)收藏:
NSMutableDictionary *_counters;
我会像这样改变你的方法,关于我不知道Items 是什么,我完全放弃了所有东西,那就是我目前拥有的:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (_counters == nil) _counters = [NSMutableDictionary dictionary];
NSString *_key = [NSString stringWithFormat:@"%03ld:%03ld", (long)indexPath.section, (long)indexPath.row];
NSInteger _currentCounterForIndexPath = [[_counters objectForKey:_key] integerValue];
[_counters setObject:@(++_currentCounterForIndexPath) forKey:_key];
}
这将为您计算每一行的点击次数,并增加每一行的点击次数。
_counter 字典将包含这样的详细信息(在我的测试应用程序的随机阶段记录):
_counter : {
"000:000" = 5;
"000:001" = 1;
"000:003" = 2;
"000:004" = 6;
"000:005" = 3;
"000:006" = 1;
}
其中AAA:BBB 是当前section (AAA) 和当前row (BBB) 中的键,以及值 是抽头次数。
所以,您可以将该集合解读为
- 在第 0 节中,第 0 行被点击了
5 次;
- 在第 0 部分中,第 1 行被点击了
1 次;
- 在第 0 节中,第 2 行被点击了
0 次; (没有任何点击此行的记录!)
- 在第 0 部分中,第 3 行被点击了
2 次;
- 在第 0 节中,第 4 行被点击了
6 次;
- 在第 0 节中,第 5 行被点击了
3 次;
- 在第 0 节中,第 6 行被点击了
1 次;
稍后,如果您想知道特定 row 在特定 section 中的点击次数,您可以重用我更新方法中的代码,例如对于第 0 部分,第 5 行:
NSString *_key = [NSString stringWithFormat:@"%03ld:%03ld", 0, 5];
NSInteger _currentCounterForIndexPath = [[_counters objectForKey:_key] integerValue];
_currentCounterForIndexPath 会有点击次数,目前是3。
我想就是这么简单。