CoreData 的簡單使用__ 02.模糊查詢和分頁

1.首先創(chuàng)建上下文 這里就不多復(fù)述了 詳見 《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];

}

//直接保存數(shù)據(jù)庫

NSError*error =nil;

[_context save:&error];

if(error) {

NSLog(@"%@",error);

}

}

(2)模糊查詢

-(void)readEmployee{

// 1.FectchRequest抓取請求對象

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

// 3.設(shè)置排序

//身高的升序排序

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

request.sortDescriptors=@[heigtSort];


//名字以"jasoneIo1"開頭

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í)行請求

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.設(shè)置排序

//身高的升序排序

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

request.sortDescriptors=@[heigtSort];

//總有共有15數(shù)據(jù)

//每次獲取6條數(shù)據(jù)

//第一頁0,6

//第二頁6,6

//第三頁12,6 3條數(shù)據(jù)

//分頁的起始索引

request.fetchOffset=12;

//分頁的條數(shù)

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

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容