【问题标题】:Show only some of the objects in an Array仅显示 Array 中的部分对象
【发布时间】:2013-05-09 20:23:15
【问题描述】:

我想只显示数组中的一些项目,但不知道该怎么做。

这是我目前显示数组中所有对象的代码:

@property (strong, nonatomic) NSArray *springs;
@property (strong, nonatomic) NSMutableArray *leafs;


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"standardCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    Spring *spring = [springs objectAtIndex:indexPath.section];  // 13 objects
    Leaf *leaf = [spring.leafs objectAtIndex:indexPath.row];  // 30 objects

    cell.textLabel.text = league.shortName;
    return cell;
}

所以我想只显示我创建的数组中的 30 个 叶对象中的 5 个,而不是全部显示。有什么办法吗?

(我正在使用 API 将项目拉入数组)

感谢您的帮助,将发布所需的任何特定代码或其他信息!

编辑 根据请求添加:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    Spring *spring = [springs objectAtIndex:section];
    return spring.leafs.count;
}

我正在使用 RestKit 进行对象映射。

【问题讨论】:

    标签: ios xcode nsarray restkit


    【解决方案1】:

    使用[NSArray objectsAtIndexes:] (reference) 获取数组的子集。

    Leaf *leaf = [spring.leafs objectAtIndex:indexPath.row]; 
    
    // This will include objects 0-4:
    NSRange range = NSMakeRange(0, 5);
    NSArray *subset = [leaf objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:range]];
    

    只需将range 调整为子集中您想要的任何开始/长度。

    编辑:当然,此方法中的任何子集逻辑也必须在 numberOfRowsInSection: 委托方法中复制,否则您的应用程序将引发异常。

    【讨论】:

    • 感谢您的回复,这很有意义,但是当我尝试它时,NSRange 行给了我一个错误,提示“使用不兼容类型 NSRange 的表达式初始化 NSRange ...知道为什么吗?
    • @Reez 不,我不明白。您可以忘记NSMakeRange(),而只需明确设置range.locationrange.length
    • 我将 range 设为指针而不是结构,我的错。我现在遇到的问题是,对于我的 textLabel 我不能再使用league.shortName,但我也不能只使用subset.shortName,那我会用什么呢?再次感谢-
    • @Reez 其他地方有一个错误,恐怕超出了这个问题的范围(这是不相关的)。
    • 据我所知,这似乎与我现在无法在新创建的数组subset 上调用属性shortName 的事实有关,我可以在哪里做league 之前。
    【解决方案2】:

    在你的tableView:numberOfRowsInSection 中怎么样,不要返回一个完整的完整的 spring.leafs?例如,

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return 5;
    }
    

    您是在尝试延迟加载它们,还是其余的都无关紧要?祝你好运。

    【讨论】:

    • 其余的都无所谓。感谢您的回复!当我尝试返回 5 时,我得到的是消息“*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]”的崩溃
    • 是的,数组是空的。检查你在哪里填充数组的方法,看看为什么它没有被填充。
    • 只是在黑暗中拍摄,leafs 被实例化为 NSMutableArray 了吗?
    • 该数组在我的原始代码中不是空的,但就在我执行 return 5;... 所以我试图弄清楚如何将我的原始代码与你的代码混搭.有什么想法吗?
    • 是的,我在上面的代码中已经知道它是一个 NSMutableArray。我需要把它变成一个 NSArray 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多