You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C中能否将IndexPath值插入NSSet?CollectionView已浏览单元格记录失效问题

问题分析与解决方案

我帮你揪出问题根源啦!你没法用NSSet记录已浏览单元格,主要是两个关键错误导致的,咱们一步步修复:

1. 可变集合未初始化

你的indexPathsOfSeenCells属性只做了声明,但从来没有创建实例,它一直是nil状态,调用任何集合方法自然都不会生效。在viewDidLoad里补上初始化代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.impressionEventStalker = [[ImpressionStalker alloc] initWithMinimumPercentageOfCell:0.70 collectionView:Collection_view delegate:self];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    appDelegate.myViewController = self;
    // 初始化可变集合,这一步必须加!
    self.indexPathsOfSeenCells = [NSMutableSet new];
}

2. 错误使用集合添加方法

你现在用的setByAddingObject:是不可变集合NSSet的方法,它只会返回一个新的集合,完全不会修改你手里的NSMutableSet。要修改原集合,得用NSMutableSet专属的addObject:方法:

修改sendEventForCellAtIndexPath:方法:

- (void)sendEventForCellAtIndexPath:(NSIndexPath * _Nonnull)indexPath {
    CustomCollectionViewCell *cell = (CustomCollectionViewCell*)[Collection_view cellForItemAtIndexPath:indexPath];
    cell.cellBackground.backgroundColor = [UIColor greenColor];
    // 替换错误的方法为addObject:
    [_indexPathsOfSeenCells addObject:indexPath];
    NSLog(@"已浏览单元格数量: %lu",(unsigned long)_indexPathsOfSeenCells.count);
}

3. 额外优化:简化Cell复用状态判断

因为UICollectionView会复用Cell,你原本的判断逻辑是对的,这里可以稍微简化一下提升可读性:

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL_ID" forIndexPath:indexPath] ;
    [cell configure:[NSString stringWithFormat:@"%ld", indexPath.row] configure: NO];
    
    // 简化三目运算符判断
    cell.cellBackground.backgroundColor = [_indexPathsOfSeenCells containsObject:indexPath] ? [UIColor greenColor] : [UIColor redColor];
    
    return cell;
}

做完这些修改后,滑动CollectionView时已浏览的Cell会正常变成绿色,indexPathsOfSeenCells也能正确记录所有已浏览的IndexPath,调用sendStalkDataToServer就能返回正确的集合啦。

内容的提问来源于stack exchange,提问作者Aviav Sabag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:07:31