Using NSPredicate to filter array of arrays

荒凉一梦 提交于 2019-12-20 10:20:51

问题


I have the following situation:

NSArray(
    NSArray(
        string1,
        string2,
        string3,
        string4,
        string5,
    )
    ,
    NSArray(
        string6,
        string7,
        string8,
        string9,
        string10,
   )
)

Now I need a predicate that returns the array that contains a specific string. e.g. Filter Array that contains string9 -> I should get back the entire second array because I need to process the other strings inside that array. Any ideas?


回答1:


Just for completeness: It can be done using predicateWithFormat::

NSArray *array = @[
    @[@"A", @"B", @"C"],
    @[@"D", @"E", @"F"],
];

NSString *searchTerm = @"E";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF == %@", searchTerm];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%@", filtered);

Output:

(
    (
        D,
        E,
        F
    )
)



回答2:


From what I know you can't do it as a one-liner so instead of using predicateWithFormat: you should use predicateWithBlock:

Something like this should do what you want

NSString *someString = @"Find me"; // The string you need to find.
NSArray *arrayWithArrayOfStrings = @[]; // Your array
[arrayWithArrayOfStrings filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSArray *evaluatedArray, NSDictionary *bindings) {
    return [evaluatedArray indexOfObject:someString] != NSNotFound;
 }]];

Update: Martin R proved me wrong :)



来源:https://stackoverflow.com/questions/17228194/using-nspredicate-to-filter-array-of-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!