Search code examples
iosobjective-cnsmutablearraynspredicatequickblox

NSPredicate for Array of Quickblox Custom Objects


I have a NSMutableArray which contains a large number of QuickBlox Custom Objects (QBCOCustomObject class).

When my user's enter name information into a textfield, I want to filter my tableview to show results based on their search.

Here's how I would get the user's full name from the custom class...

for (QBCOCustomObject *object in self.userArray) { 
    NSString *c = [object.fields[@"fullName"];
    NSLog (@"%@", c);
}

In the method below I am trying to setup the predicate but I'm struggling to find the correct format for the predicate. Can anyone help?

- (void)textFieldDidChange :(UITextField *)theTextField {

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(fullName CONTAINS[cd] %@)", self.searchBar.text];
    self.userArray = [[self.userArray filteredArrayUsingPredicate:predicate] mutableCopy];
    [self.tableView reloadData];

}

Solution

  • Here is the working example:

    NSMutableArray *initialArray = [NSMutableArray array];
    
    QBCOCustomObject *object1 = [QBCOCustomObject customObject];
    object1.fields = [@{
        @"fullName": @"Igor",
        @"age": @(27)
    } mutableCopy];
    [initialArray addObject:object1];
    //
    QBCOCustomObject *object2 = [QBCOCustomObject customObject];
    object2.fields = [@{
                        @"fullName": @"Bob",
                        @"age": @(27)
                        } mutableCopy];
    [initialArray addObject:object2];
    //
    QBCOCustomObject *object3 = [QBCOCustomObject customObject];
    object3.fields = [@{
                        @"fullName": @"Igorio",
                        @"age": @(27)
                        } mutableCopy];
    [initialArray addObject:object3];
    
    NSLog(@"initialArray: %@", initialArray);
    
    NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"fields.fullName CONTAINS 'Igor'"];
    NSArray *filteredArray = [initialArray filteredArrayUsingPredicate:bPredicate];
    
    NSLog(@"filteredArray: %@", filteredArray);
    

    It returns the 'Igor' and 'Igorio' objects and skip 'Bob'

    Here is a good tutorial about NSPredicate with great examples:

    http://nshipster.com/nspredicate/