1.首先創(chuàng)建上下文 這里就不多復(fù)述了 詳見(jiàn) 《CoreData 的簡(jiǎn)單使用__ 01》皱蹦。
2.(1)我們先添加多條信息來(lái)方便我們的模糊查詢(xún)操作,代碼如下:
-(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];
}
//直接保存數(shù)據(jù)庫(kù)
NSError*error =nil;
[_context save:&error];
if(error) {
NSLog(@"%@",error);
}
}
(2)模糊查詢(xún)
-(void)readEmployee{
// 1.FectchRequest抓取請(qǐng)求對(duì)象
NSFetchRequest*request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 3.設(shè)置排序
//身高的升序排序
NSSortDescriptor*heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height"ascending:YES];
request.sortDescriptors=@[heigtSort];
//名字以"jasoneIo1"開(kāi)頭
NSPredicate*pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"jasoneIo1"];
request.predicate= pre;
//名字以"1"結(jié)尾
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.執(zhí)行請(qǐng)求
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) 分頁(yè)查詢(xún)?
-(void)pageSeacher{
// 1.FectchRequest抓取請(qǐng)求對(duì)象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 3.設(shè)置排序
//身高的升序排序
NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height"ascending:YES];
request.sortDescriptors=@[heigtSort];
//總有共有15數(shù)據(jù)
//每次獲取6條數(shù)據(jù)
//第一頁(yè)0,6
//第二頁(yè)6,6
//第三頁(yè)12,6 3條數(shù)據(jù)
//分頁(yè)的起始索引
request.fetchOffset=12;
//分頁(yè)的條數(shù)
request.fetchLimit=6;
// 4.執(zhí)行請(qǐng)求
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);
}
}