NSPredicate 的使用(持续更新)

来源:互联网 发布:软件界面设计素材 编辑:程序博客网 时间:2024/05/22 15:22

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] 比较操作 (>,<,>=,<=,=)

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

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

[3] 范围 (between,in)

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

[4] 通配符 (like)

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

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

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

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

[6] 正则表达式

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

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

[7] keypath

0 0
原创粉丝点击