在搜索中是否有一些Objective-C魔术来获得外部数组的索引



我有一个包含数组的数组。容器就是这样:

NSArray *container = @[
@[ @(12), @(23), @(34), @(11)],  // index 0 
@[ @(32), @(12), @(12), @(78)],  // index 1
@[ @(14), @(97), @(45), @(82)],  // index 2
@[ @(67), @(20), @(46), @(12)],  // index 3
]

所有内部阵列具有相同数量的元素。

假设我想查看 @(45)是否存储在容器内部的任何数组中,如果是正面的,则要获取该子阵列的索引,在这种情况下,请参见索引2(请参阅代码中的注释)。

我知道如何使用枚举来做到这一点。我正在寻找的是,如果有一些魔术可以用较少的代码(我知道Objective-C有很多魔术晦涩的命令)来完成所有事情)。

)。

我知道我可以做这样的事情,以获取数组,给定元素

NSString *search = @(45);
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF CONTAINS %@", search];
NSArray *array = [container filteredArrayUsingPredicate: predicate];
NSLog(@"result: %@", array);

但是容器上该数组的索引呢?

谢谢

NSArrayindexOfObjectPassingTest:方法可以返回符合条件的对象的第一个索引:

int value = 12;
NSUInteger idx = [container indexOfObjectPassingTest:
    ^BOOL (NSArray* subArray, NSUInteger idx, BOOL *stop) {
        return *stop = [subArray containsObject:@(value)];
}];

您可以使用 indexofObject在数组中获得对象的索引:方法。

您可以这样做:

NSString *search = @(45);
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF == %@", search];
// Filtered is an array which contains the result (Means the filtered array contains the index 2 array - array of array)
NSArray *filtered = [container filteredArrayUsingPredicate: predicate];
// Using `indexOfObject:` method for getting the result
NSLog(@"Index %d", [container indexOfObject:[filtered objectAtIndex:0]]);

最新更新