加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 使用NSIndexPath作为NSMutableDictionary中的关

发布时间:2020-12-16 05:55:25 所属栏目:百科 来源:网络整理
导读:有没有什么特别的原因为什么尝试使用NSIndexPath作为密钥存储和检索NSMutableDictionary中的值可能会失败? 我最初尝试这样做,以便为UITableView存储一个UITableViewCell高度(self.cellHeights)的NSMutableDictionary.每次点击UITableViewCell,该单元格将根
有没有什么特别的原因为什么尝试使用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,那么一切正常.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读