ios - 将标记项正确添加到 nsmutable 数组中

标签 ios iphone objective-c nsmutablearray uicollectionview

我正在尝试将所有 cell.img.tag 添加到我的 nsmutable 数组中。但是,我尝试了多种方法来执行此操作,例如 for 循环,但每次结果都不正确。我需要将每个单独的标签添加到 NSMutableArray 中。我将在下面发布我的代码来给你一个想法。注意:这只是为了展示我正在做的事情,这不是我尝试用来完成这项工作的方法。

  - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
 {
    Cell *cell = (Cell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    NSString *string = [addressString valueForKey:@"number"];
    array = [[NSMutableArray alloc]init];
    cell.img.tag = string.intValue;
    [array addObject:[NSNumber numberWithInt:cell.img.tag]];
    return cell;
 }

编辑:当我使用 for 循环时,它会显示所有标签,但最终会创建多个数组,每个数组中的值相同,就像这样重复多次。 (1,1,1)(2,2,2)。

最佳答案

这一行是问题所在:

array = [[NSMutableArray alloc]init];

每次调用 cellForItemAtIndexPath 函数时,您基本上都会销毁数组并创建一个新的空数组。

将该行移到代码中的其他位置(例如,在 init 方法中)。

关于ios - 将标记项正确添加到 nsmutable 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22084072/

相关文章:

ios - 使用 UIImage RenderingMode AlwaysTemplate 在 iPhone 6 上显示不同的颜色

iphone - Windows 上的 DragonFireSDK 和 iPhone 开发

c++ - 在 iOS 项目中将 c++ 与 objective-c 集成

ios - Sprite 套件场景中来自 Vungle 的视频广告

ios - UITableViewCell 为不同的方向和单元格类型加载自定义 XIB

ios - 无法识别的选择器发送到实例 Swift 2.1 - 日期选择器

objective-c - 比较 objective-C 中的 2 个字符串

ios - 如何在不丢失自动布局的情况下重新定位 ImageView?

iphone - 捕获输出 :didOutputSampleBuffer:fromConnection Performance Issues

iOS:使用 Core Graphics 绘制 "Movable Polygon"