【问题标题】:How can I select elements from an NSArray according to array of NSIndexPaths如何根据 NSIndexPaths 数组从 NSArray 中选择元素
【发布时间】:2014-03-09 12:06:03
【问题描述】:

有没有一种快速的方法可以从UITableViewNSArray of NSIndexPaths)返回的数组中获取索引处的所有元素。

例如:

[self.dataSourceArray selectItemsAt:[self.tableView indexPathsForSelectedItems]]

【问题讨论】:

  • “快”是什么意思?最短的代码?

标签: ios objective-c nsarray nsindexpath nsindexset


【解决方案1】:

没有内置方法,但您可以简单地遍历选定的行 (假设只有一节)并添加相应的元素 到一个可变数组:

NSMutableArray *selectedObjects = [NSMutableArray array];
for (NSIndexPath *indexPath in [self.tableView indexPathsForSelectedRows]) {
    [selectedObjects addObject:self.dataSourceArray[indexPath.row]];
}

【讨论】:

    【解决方案2】:

    你要找的词是 Lambda

    有两种方法

    您可以在链接中查找它

    Does Objective-C have List Lambda Query like C#?

    应该是这样的

    NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
           for(NSIndexPath i in [self.tableView indexPathsForSelectedItems]){
                    if(i.row == evaluatedObject.row){
                       return YES;
                    }
            }
           return NO;
    }];
    NSArray *result = [self.dataSourceArray filteredArrayUsingPredicate:p];
    

    【讨论】:

    • 这个问题的答案有点模糊。你能详细说明一下或发布一个例子吗?
    【解决方案3】:

    使用 NSArray 的objectsAtIndexes: 方法。

    NSMutableIndexSet *mutableIndexSet = [[NSMutableIndexSet alloc] init];
    
    // Add all indexes to NSMutableIndexSet
    for (int i = 0; i < [self.tableView indexPathsForSelectedRows].count; i++) {
        [mutableIndexSet addIndex: ((NSIndexPath *) [self.tableView indexPathsForSelectedRows][i]).row];
    }
    
    [self.dataSourceArray objectsAtIndexes:mutableIndexSet];
    

    【讨论】:

    • objectsAtIndexes:NSIndexSet 作为参数。
    • @NikolaiRuhe 已编辑答案。
    • 先创建索引集有什么好处?您可以在循环中直接将所选项目添加到可变数组中。
    • @MartinR 因为objectsAtIndexes: 要求NSMutableIndexSet,而不是NSArray
    猜你喜欢
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多