CoreData 的简单使用__ 02.模糊查询和分页

1.首先创建上下文 这里就不多复述了 详见 《CoreData 的简单使用__ 01》


2.(1)我们先添加多条信息来方便我们的模糊查询操作,代码如下:

-(void)addEmployee{

for(inti =0; i <15; i++) {

Employee*emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];

emp.name= [NSString stringWithFormat:@"jasoneIo%d",i];

emp.height=@(1.80+ i);

emp.birthday= [NSDate date];

}

//直接保存数据库

NSError*error =nil;

[_context save:&error];

if(error) {

NSLog(@"%@",error);

}

}

(2)模糊查询

-(void)readEmployee{

// 1.FectchRequest抓取请求对象

NSFetchRequest*request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];

// 3.设置排序

//身高的升序排序

NSSortDescriptor*heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height"ascending:YES];

request.sortDescriptors=@[heigtSort];


//名字以"jasoneIo1"开头

NSPredicate*pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH%@",@"jasoneIo1"];

request.predicate= pre;

//名字以"1"结尾

NSPredicate*pre = [NSPredicate predicateWithFormat:@"nameENDSWITH%@",@"1"];

request.predicate= pre;

//名字包含"eIo11"

NSPredicate*pre = [NSPredicate predicateWithFormat:@"name CONTAINS%@",@"eIo11"];

request.predicate= pre;

// like

NSPredicate*pre = [NSPredicate predicateWithFormat:@"name like%@",@"*eIo1*"];

request.predicate= pre;

// 4.执行请求

NSError*error =nil;

NSArray*emps = [_context executeFetchRequest:requesterror:&error];

if(error) {

NSLog(@"error");

}

//NSLog(@"%@",emps);

//遍历员工

for(Employee*emp in emps) {

NSLog(@"名字%@身高%@生日%@",emp.name,emp.height,emp.birthday);

}

(3) 分页查询 

-(void)pageSeacher{

// 1.FectchRequest抓取请求对象

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];

// 3.设置排序

//身高的升序排序

NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height"ascending:YES];

request.sortDescriptors=@[heigtSort];

//总有共有15数据

//每次获取6条数据

//第一页0,6

//第二页6,6

//第三页12,6 3条数据

//分页的起始索引

request.fetchOffset=12;

//分页的条数

request.fetchLimit=6;

// 4.执行请求

NSError*error =nil;

NSArray*emps = [_context executeFetchRequest:requesterror:&error];

if(error) {

NSLog(@"error");

}

//NSLog(@"%@",emps);

//遍历员工

for(Employee*emp in emps) {

NSLog(@"名字%@身高%@生日%@",emp.name,emp.height,emp.birthday);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值