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

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容