objective-c – 使用NSIndexPath作为NSMutableDictionary中的关
有没有什么特别的原因为什么尝试使用NSIndexPath作为密钥存储和检索NSMutableDictionary中的值可能会失败?
我最初尝试这样做,以便为UITableView存储一个UITableViewCell高度(self.cellHeights)的NSMutableDictionary.每次点击UITableViewCell,该单元格将根据存储在该特定indexPath的NSMutableDictionary中的值在两个不同的高度之间展开或缩小: - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSNumber *heightNSNumber = [self.cellHeights objectForKey:indexPath]; if (!heightNSNumber) { heightNSNumber = [NSNumber numberWithFloat:100.0]; [self.cellHeights setObject:heightNSNumber forKey:indexPath]; } return [heightNSNumber floatValue]; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; NSNumber *heightNSNumber = [self.cellHeights objectForKey:indexPath]; if (!heightNSNumber) { heightNSNumber = [NSNumber numberWithFloat:100.0]; [self.cellHeights setObject:heightNSNumber forKey:indexPath]; } if ([heightNSNumber floatValue] == 100.0) { [self.cellHeights setObject:[NSNumber numberWithFloat:50.0] forKey:indexPath]; } else { [self.cellHeights setObject:[NSNumber numberWithFloat:100.0] forKey:indexPath]; } [tableView beginUpdates]; [tableView endUpdates]; } 由于我不知道的原因,通过[self.cellHeights objectForKey:indexPath]获取单元格的高度在tableView:didSelectRowAtIndexPath:工作正常.但是,尝试获取tableView中的单元格高度:heightForRowAtIndexPath:通过[self.cellHeights objectForKey:indexPath]总是返回nil,因为似乎用于存储高度的indexPath与用于获取单元格高度的indexPath不匹配,即使它们对indexPath.section和indexPath.row具有相同的值.因此,将“相同”索引路径的新对象添加到self.cellHeights中(显而易见,因为self.cellHeights.count此后增加). 当您使用行([NSNumber numberWithInteger:indexPath.row])将单元格高度存储在NSMutableDictionary中时,这不会发生,所以这是我现在在做的,但是我想了解为什么indexPath不工作的关键. 解决方法
虽然我讨论迟到,这里是一个快速简单的解决方案,可以让您使用NSIndexPath实例作为字典键.
只需通过添加以下行重新创建indexPath: indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]; 瞧. tableView:heightForRowAtIndexPath:内部使用NSMutableIndexPath实例(就像使用断点看到的那样).不知何故,在计算哈希键时,这些实例似乎与NSIndexPath不协调. 通过将其转换回NSIndexPath,那么一切正常. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 【Cocos2d入门教程六】Cocos2d-x事件篇之触摸
- ruby-on-rails – nil的未定义方法`update’:NilClass rai
- React语法基础之JSX
- 从应用层次探讨Reactor
- ruby-on-rails – 当在本地使用Rails 4时使用rbtrace时,如何
- c# – 从ASMX Web服务捕获自定义异常
- .net – 警告:在同一个依赖程序集的不同版本之间发现冲突
- ios – 如何为一个视图控制器设置UINavigation栏的titletex
- sqlite3 not found 解决方案
- ruby-on-rails – ENOTFOUND:getaddrinfo ENOTFOUND api.h