【问题标题】:How get objects from one array with same properties of other?如何从一个数组中获取具有其他相同属性的对象?
【发布时间】:2016-11-25 10:18:55
【问题描述】:

例如: 我有两个NSMutableArray。一个@[1,2,3,4,5,6,7]。其他有像

这样的对象
@[
   @{@idObjectToSearch":1, @"name":@"aaaaa", @"surname": @"bbbbb"}, @{@idObjectToSearch":2, @"name":@"aaaaa", @"surname": @"ccccc"},
    ...
   @{@idObjectToSearch":100, @"name":@"aaaaa", @"surname": @"cccdcd"}
];

那么我怎样才能更有效地从第二个数组中提取所需的对象呢?

【问题讨论】:

  • 这两个数组之间的联系是什么,基于您要从第二个数组中提取对象的内容?
  • @Rajat 我需要“idObjectToSearch”的所有对象
  • 除非您想将第二个数组中的对象加载到由idObjectToSearch 值键入的字典中(这就是我会做的),否则您使用的任何技术都将是数组的线性搜索

标签: ios objective-c nsmutablearray nsarray nsset


【解决方案1】:

您需要在第二个数组中使用NSPredicate

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"idObjectToSearch IN %@", firstArray];
//In above predicate instead of passing `1` you need to pass object from first array that you want.

NSArray *filterArray = [secondArray filteredArrayUsingPredicate:predicate];

//Now access Array objects
if (filterArray.count > 0) {
     NSLog(@"%@",filterArray);
}

【讨论】:

  • 它只返回一个对象,但我需要全部 7 个,如示例所示。所以我可以用 OR 形成一个长谓词,但我认为这不是我的情况的好方法。
  • @Viktorianec 那么你需要使用IN 检查编辑后的答案
【解决方案2】:

你可以这样做

NSMutableArray * arrSorted = [NSMutableArray new];
for(int i=0;i<arr.count;i++) {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"idObjectToSearch == %@", firstArray[i]];
    NSUInteger index = [secondArray indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
        return [predicate evaluateWithObject:obj];
    }];
    if (index != NSNotFound) {
        [arrSorted addObject:[arrM objectAtIndex:index]];
    }
}

arrSorted 将包含您的排序数据

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2018-04-08
    • 2019-06-05
    • 2018-12-26
    相关资源
    最近更新 更多