簡體   English   中英

是否有一些Objective-C的魔術來獲取搜索中外部數組的索引?

[英]Is there some objective-c magic to obtain the index of the outside array in a search?

我有一個包含數組的數組。 容器是這樣的:

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]]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM