Frage

I have a NSArray of NSDictionary.

One of the keys of the NSDictionary contains a NSArray of strings.

Is there a way that I can use NSPredicate to find a specific strins in that Array of strings?

Thanks :)

Also: This work great, but not for sublevelArray

predicate = [NSPredicate predicateWithFormat:@" %K LIKE[cd] %@", sKey, sLookForString];
War es hilfreich?

Lösung

Just replace LIKE with CONTAINS in your format string. For example, given this array:

NSArray *dogs = @[@{@"name" : @"Fido",
                    @"toys" : @[@"Ball", @"Kong"]},
                  @{@"name" : @"Rover",
                    @"toys" : @[@"Ball", @"Rope"]},
                  @{@"name" : @"Spot",
                    @"toys" : @[@"Rope", @"Kong"]}];

...the following predicate can be used obtain a filtered array containing only the dictionaries where the value for the key toy is an array that contains the string Kong.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K CONTAINS[cd] %@", @"toys", @"Kong"];

Andere Tipps

On NSArray you can use filteredArrayUsingPredicate:, on NSDictionary use enumerateKeysAndObjectsUsingBlock: and then for each value do either a filteredArrayUsingPredicate: if it is an NSArray or you can use evaluateWithObject: using the predicate itself.

If you want to filter the array of dictionaries based on the array of strings, you can use -predicateWithBlock to filter the array, as shown in the code below:

- (NSArray *)filterArray:(NSArray *)array WithSearchString:(NSString *)searchString {
    NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        NSDictionary *dictionary = (NSDictionary *)evaluatedObject;
        NSArray *strings = [dictionary objectForKey:@"strings"];

        return [strings containsObject:searchString];
    }];

    return [array filteredArrayUsingPredicate:predicate];
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top