NSPredicate谓词过滤NSDictionary、NSSt

2018-11-13  本文已影响0人  oc123

话不多说,上栗子!

  • self.contacts数组中元素是NSString
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self contains[cd] %@", text];
self.filteredContacts = [self.contacts filteredArrayUsingPredicate:predicate];
NSLog(@"筛选出self.contacts中元素,包含text变量的元素:%@", self.filteredContacts);
  • self.contacts数组中元素是NSDictionary
// 注意:其中Name是self.contacts中参与筛选的一个Key
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Name CONTAINS[cd] %@", text];
self.filteredContacts = [self.contacts filteredArrayUsingPredicate:predicate];
NSLog(@"筛选出self.contacts中元素key为Name的对象,包含text变量的元素:%@", self.filteredContacts);

下方内容来自:https://blog.csdn.net/sinat_24363257/article/details/50420374

  • 使用NSPredicate比较两个数组中相同(不同)的元素
    //把数据源拿出来创建临时的数组,不要直接使用数据源
    NSArray *answer = @[@1, @2, @3];//答案数组
    NSArray *select = @[@1, @4];    //用户选的选项
    
    if ([answer isEqualToArray:select]) {
        //一样就是对的
 
    }else {
        //不一样就是错的
        //拿出来answer 和 select 中一样的
        NSArray *selectTure = [answer filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF in %@", select]];
        NSLog(@"用户选择对的 -> %@", selectTure);
        
        NSArray *selectWrong = [select filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT (SELF in %@)", answer]];
        NSLog(@"用户选择是错的 -> %@", selectWrong);
        
        NSArray *unselectTure = [answer filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT (SELF in %@)", selectTure]];
        NSLog(@"用户没选择的正确答案 -> %@", unselectTure);
        
    }
filteredArrayUsingPredicate: 方法 与 filterUsingPredicate:方法的区别
- (void)filterUsingPredicate:(NSPredicate *)predicate;    // 因为是可变数组,直接过滤掉满足条件的元素
- (NSArray<ObjectType> *)filteredArrayUsingPredicate:(NSPredicate *)predicate;    // 因为是不可变数组,过滤掉满足条件的元素,返回一个不可变数组
上一篇 下一篇

猜你喜欢

热点阅读