NSPredicate用于Quickblox自定义对象数组

时间:2015-10-16 07:55:10

标签: ios objective-c nsmutablearray nspredicate quickblox

我有一个NSMutableArray,其中包含大量QuickBlox自定义对象(QBCOCustomObject类)。

当我的用户在文本字段中输入名称信息时,我想过滤我的tableview以根据他们的搜索显示结果。

以下是我如何从自定义类中获取用户的全名...

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

在下面的方法中,我尝试设置谓词,但我很难找到谓词的正确格式。有人可以帮忙吗?

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

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

}

1 个答案:

答案 0 :(得分:1)

以下是工作示例:

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

它返回'Igor'和'Igorio'对象并跳过'Bob'

这是一个关于NSPredicate的好教程,有很好的例子:

http://nshipster.com/nspredicate/