Coredata第三課數(shù)據(jù)查詢

問題

小明班上最近月考了,老師大明想要給一部分優(yōu)秀的同學(xué)進(jìn)行獎(jiǎng)勵(lì),而另外一部分要進(jìn)行查漏補(bǔ)缺。大明決定將總分排名前10的,各科成績排名前10的以及排名最后10名的按從高到低的順序找出來。以前大明都是在家用筆一個(gè)個(gè)劃出來。不過最近大明在長沙戴維營教育接受了殘酷的iOS培訓(xùn),決定裝逼一把,給自己的“腎6+”開發(fā)了一款應(yīng)用。只要各科老師將成績提交給他,就可以直接看到這些學(xué)生的成績了,并且各種曲線、柱狀圖、餅圖。每個(gè)學(xué)生的情況就好比沒穿衣服一樣”透明“?,F(xiàn)在的問題是,大明并不想自己去實(shí)現(xiàn)各種篩選和排序算法。

創(chuàng)新互聯(lián)長期為近1000家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為漢南企業(yè)提供專業(yè)的成都網(wǎng)站建設(shè)、成都做網(wǎng)站,漢南網(wǎng)站改版等技術(shù)服務(wù)。擁有十載豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。

解決方法

很快大明就想到了戴維營教育的博客上Core Data除了簡單的存取功能外,還具備各種取數(shù)據(jù)的方法。

一、數(shù)據(jù)獲取

Core Data中獲取數(shù)據(jù)必須通過NSFetchRequest進(jìn)行。我們有兩種方式獲取NSFetchRequest對象。

  • 通過實(shí)體名稱創(chuàng)建NSFetchRequest對象。

這種方式其實(shí)就是我們在前面兩篇文章中用來獲取數(shù)據(jù)的技巧。

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];//或者NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];fetchRequest.entity = entity;
  • 通過模型文件中創(chuàng)建的請求模版創(chuàng)建。

Coredata第三課 數(shù)據(jù)查詢

//使用managedModel獲取fetchRequest模版NSFetchRequest *fetchRequest = [appDelegate.managedObjectModel fetchRequestTemplateForName:@"personFR"];
  • 我們可以指定fetchRequest的結(jié)果類型來獲取不同數(shù)據(jù),如存儲的對象、結(jié)果數(shù)目等。

//    NSFetchRequest *fetchRequest = [appDelegate.managedObjectModel fetchRequestTemplateForName:@"personFR"];
    //如果需要改變結(jié)果的類型,不能使用從模版生成的request對象
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    //獲取結(jié)果總數(shù)
    fetchRequest.resultType = NSCountResultType;

不過我們也不只一種獲取結(jié)果數(shù)目的方式。在Context里面提供了一系列的操作request的方法,其中就包括了獲取結(jié)果數(shù)目的功能。

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];//獲取結(jié)果數(shù)目NSUInteger count = [context countForFetchRequest:fetchRequest error:nil];
二、篩選結(jié)果集

大明已經(jīng)可以得到所有學(xué)生的成績信息了,接下來要做的就是對它們進(jìn)行排序和篩選。

  • 給學(xué)生成績進(jìn)行排序

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];//排序描述符,按score降序排列NSSortDescriptor *sort01 = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO];//可以同時(shí)按多個(gè)屬性進(jìn)行排序fetchRequest.sortDescriptors = @[sort01];NSArray *result = [context executeFetchRequest:fetchRequest error:nil];if (result) {
    _people = [NSMutableArray arrayWithArray:result];
    for (NSObject *obj in _people) {
        NSLog(@"%@", [obj valueForKey:@"score"]);
    }}

結(jié)果:

2015-02-04 10:54:16.599 02-02-CoreData01[5832:276345] 99
2015-02-04 10:54:16.600 02-02-CoreData01[5832:276345] 60
2015-02-04 10:54:16.600 02-02-CoreData01[5832:276345] 56
2015-02-04 10:54:16.600 02-02-CoreData01[5832:276345] 45
  • 篩選出成績排名前十的學(xué)生

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];NSSortDescriptor *sort01 = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO];fetchRequest.sortDescriptors = @[sort01];//限制只取前十,其實(shí)這是有問題的,萬一有重復(fù)的分?jǐn)?shù),后面的就取不到了。fetchRequest.fetchLimit = 10;NSArray *result = [context executeFetchRequest:fetchRequest error:nil];
  • 使用NSPredicate篩選成績高于90分的學(xué)生

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"score >= 90"];fetchRequest.predicate = predicate;
進(jìn)階

上面的這些數(shù)據(jù)獲取方式都是同步的方式,如果數(shù)據(jù)量比較大的話,會顯著的影響到程序的性能和用戶體驗(yàn)。Core Data中也提供了異步數(shù)據(jù)獲取功能。

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;NSManagedObjectContext *context = appDelegate.managedObjectContext;NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];NSSortDescriptor *sort01 = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO];fetchRequest.sortDescriptors = @[sort01];fetchRequest.fetchLimit = 2;//異步請求NSAsynchronousFetchRequest *asyncRequst = [[NSAsynchronousFetchRequest alloc] initWithFetchRequest:fetchRequest completionBlock:^(NSAsynchronousFetchResult *result) {
    for (NSObject *obj in result.finalResult) {
        NSLog(@"%@", [obj valueForKey:@"score"]);
    }}];//執(zhí)行異步請求[context executeRequest:asyncRequst error:nil];

注意: 在使用異步請求的時(shí)候,需要設(shè)置NSManagedContext對象的并發(fā)類型,否則會出錯(cuò)。

2015-02-04 12:12:50.709 02-02-CoreData01[6083:300576] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSConfinementConcurrencyType context <NSManagedObjectContext: 0x7fb27b72c5f0> cannot support asynchronous fetch request <NSAsynchronousFetchRequest: 0x7fb27b71d750> with fetch request <NSFetchRequest: 0x7fb27b7247a0> (entity: Person; predicate: ((null)); sortDescriptors: ((    "(score, descending, compare:)")); limit: 2; type: NSManagedObjectResultType; ).'

解決辦法是在創(chuàng)建Context對象的時(shí)候,設(shè)置它的并發(fā)類型。

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];if (!coordinator) {
    return nil;}//創(chuàng)建Context對象,并設(shè)置并發(fā)類型_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];[_managedObjectContext setPersistentStoreCoordinator:coordinator];
參考資料
  1. Core Data異步操作:http://code.tutsplus.com/tutorials/ios-8-core-data-and-asynchronous-fetching--cms-22241

  2. Core Data并發(fā)操作:http://code.tutsplus.com/tutorials/core-data-from-scratch-concurrency--cms-22131

  3. 批量更新Core Data:http://code.tutsplus.com/tutorials/ios-8-core-data-and-batch-updates--cms-22164

本文檔由長沙戴維營教育整理。

本文標(biāo)題:Coredata第三課數(shù)據(jù)查詢
分享鏈接:http://muchs.cn/article18/gdcjgp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)、動(dòng)態(tài)網(wǎng)站、網(wǎng)頁設(shè)計(jì)公司、移動(dòng)網(wǎng)站建設(shè)、網(wǎng)站營銷標(biāo)簽優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站