NSPredicate 的使用(持续更新)_#import

NSPredicate

谓词工具一般用于过滤数组数据,也可用来过滤CoreData查询出的数据.

1). 支持keypath

2). 支持正则表达式

 

在使用之前先新建3个类 Teacher Info Address,详细代码如下

Info.h

#import <Foundation/Foundation.h>

@interface Info : NSObject

@property (nonatomic, strong) NSString *classNum;

@end

Info.m

#import "Info.h"

@implementation Info

@end

Address.h

#import <Foundation/Foundation.h>

@interface Address : NSObject

@property (nonatomic, strong) NSString *detailAddress;

@end

Address.m

#import "Address.h"

@implementation Address

@end

Teacher.h

#import <Foundation/Foundation.h>
#import "Info.h"
#import "Address.h"

@interface Teacher : NSObject

@property (nonatomic, strong) NSString   *name;
@property (nonatomic, strong) Info       *info;
@property (nonatomic, strong) Address    *address;
@property (nonatomic, assign) NSInteger   age;

@end

Teacher.m

#import "Teacher.h"

@implementation Teacher

- (instancetype)init
{
    self = [super init];
    if (self) {
     //此处必须初始化以下对象 _info
= [[Info alloc] init]; _address = [[Address alloc] init]; } return self; } @end

 

初始化数据并添加进数组中

    //初始化数据
    Teacher *teacher1 = [[Teacher alloc] init];
    teacher1.info.classNum         = @"11班";
    teacher1.address.detailAddress = @"海淀区";
    teacher1.name                  = @"L.Y.F.";
    teacher1.age                   = 11;
    
    Teacher *teacher2 = [[Teacher alloc] init];
    teacher2.info.classNum         = @"12班";
    teacher2.address.detailAddress = @"立水桥";
    teacher2.name                  = @"P.K.";
    teacher2.age                   = 20;

    Teacher *teacher3 = [[Teacher alloc] init];
    teacher3.info.classNum         = @"11班";
    teacher3.address.detailAddress = @"万盛路";
    teacher3.name                  = @"Y.X.";
    teacher3.age                   = 22;
    
    //将数据添加进数组
    NSMutableArray *teachers =
        [[NSMutableArray alloc] initWithObjects:teacher1, teacher2, teacher3, nil];

开始正式的使用谓词

[1] 比较操作 (>,<,>=,<=,=)

NSPredicate 的使用(持续更新)_初始化_02

[2] 字符串常规操作 (beginswith,endswith,contains)

    @"name beginswith[cd] 'Y'"
    @"name endswith[cd] 'X.'"
    @"name contains[cd] 'X'"

NSPredicate 的使用(持续更新)_iOS_03

[3] 范围 (between,in)

    @"age between {10, 20}"
    @"age in {10, 20}" //这个不确定是什么

NSPredicate 的使用(持续更新)_初始化_04

[4] 通配符 (like)

注:使用?表示一个字符,*表示多个字符

    @"name like[cd] '*X*'"

NSPredicate 的使用(持续更新)_#import_05

[5] 逻辑运算 (AND,OR,NOT)

@"age <= 22 AND name like[cd] '*X*'"

NSPredicate 的使用(持续更新)_iOS_06

[6] 正则表达式

注:^Y.+.$ 以Y开头,以.结尾的字符

    @"self.name matches '^Y.+.$'"

NSPredicate 的使用(持续更新)_初始化_07

[7] keypath

NSPredicate 的使用(持续更新)_iOS_08