10

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
  • have look at it and do reply if usefull or any quetions Here Commented Jun 21, 2013 at 5:45

2 Answers 2

20

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
    )
)
Sign up to request clarification or add additional context in comments.

5 Comments

+1, I was working on this with SUBQUERY, [NSPredicate predicateWithFormat:@"SUBQUERY(SELF, $content, $content == [c] %@)",string] but this didn't work. Any pointers?
@Anupdas: You were almost there, @"SUBQUERY(SELF, $content, $content == [c] %@).@count > 0" works.
@MartinR Awesome, it works. So the result of the subquery should be equated to some for even forming the predicate. Thanks :)
@Anupdas: Exactly, the SUBQUERY returns a set, but the predicate must evaluate to true or false.
is it possible to get only E as element of nested array
1

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.