1.首先創(chuàng)建上下文 這里就不多復述了 詳見 《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.執(zhí)行請求
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.執(zhí)行請求
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);
}
}