CoreData Third Lesson data query

Source: Internet
Author: User

Problem

Xiao Ming's class recently monthly exam, the teacher daming want to give some excellent students to reward, and another part of the leak to check the vacancy. Daming decided to rank the top 10 of the total, the top 10 of the subjects ' scores and the last 10 ranked in order from high to low. Before Daming was at home with a pen to draw out. However, Daming recently received a brutal iOS training at Camp David in Changsha, and decided to put on a push to develop an application for his "kidney 6+". As long as the teachers will submit the results to him, you can directly see the results of these students, and various curves, histogram, pie chart. Each student's situation is "transparent" as if it were naked. The problem now is that Daming doesn't want to implement various filtering and sorting algorithms on his own.

Workaround

Soon Daming thought of the Camp David Education blog. Core data has a variety of methods for fetching data, in addition to simple access functions.

First, data acquisition

The data in Core must be obtained through NSFetchRequest . We have two ways of getting NSFetchRequest objects.

    • Creates an object from the entity name NSFetchRequest .

This is actually the technique we used to get the data in the previous two articles.

Nsfetchrequest *fetchrequest = [nsfetchrequest fetchrequestwithentityname:@ "person"];//or nsfetchrequest * Fetchrequest = [[Nsfetchrequest alloc] init]; Nsentitydescription *entity = [nsentitydescription entityforname:@ "person" inmanagedobjectcontext:context]; Fetchrequest.entity = entity;
    • Created through the request template created in the model file.

650) this.width=650; "src=" Http://io.diveinedu.com/images/person_fetch_request.png "/>

Use Managedmodel to get fetchrequest template nsfetchrequest *fetchrequest = [Appdelegate.managedobjectmodel fetchrequesttemplateforname:@ "PERSONFR"];
    • We can specify the result type of fetchrequest to get different data, such as stored objects, number of results, etc.

Nsfetchrequest *fetchrequest = [Appdelegate.managedobjectmodel fetchrequesttemplateforname:@ "PersonFR"]; If you need to change the type of the result, you cannot use the request object generated from the template nsfetchrequest *fetchrequest = [Nsfetchrequest fetchrequestwithentityname:@ "    Person "]; Get total results fetchrequest.resulttype = Nscountresulttype;

But we have more than one way to get the number of results. The context provides a series of methods for manipulating the request, including the ability to obtain the number of results.

Nsfetchrequest *fetchrequest = [nsfetchrequest fetchrequestwithentityname:@ "Person"];//get the number of results nsuinteger count = [ Context Countforfetchrequest:fetchrequest Error:nil];
Second, filter the result set

Daming can get all the student's grades, and the next thing to do is sort and filter them.

    • To sort out students ' grades

nsfetchrequest * fetchrequest = [nsfetchrequest fetchrequestwithentityname:@ "Person"];//sort descriptor, Sort nssortdescriptor *sort01 = [nssortdescriptor sortdescriptorwithkey:@ "score" in descending order of score  ascending:no];//can be sorted by multiple properties at the same time 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"]);     }} 

Results:

2015-02-04 10:54:16.599 02-02-coredata01[5832:276345] 992015-02-04 10:54:16.600 02-02-coredata01[5832:276345] 602015-02-04 10:54:16.600 02-02-coredata01[5832:276345] 562015-02-04 10:54:16.600 02-02-CoreData01[5832:276345] 45
    • Sift out the top ten students

Nsfetchrequest *fetchrequest = [nsfetchrequest fetchrequestwithentityname:@ "person"]; Nssortdescriptor *sort01 = [nssortdescriptor sortdescriptorwithkey:@ "score" ascending:no]; Fetchrequest.sortdescriptors = @[sort01];//Limit only take the first 10, in fact, this is problematic, in case there are repeated scores, the back will not be taken. Fetchrequest.fetchlimit = 10; Nsarray *result = [context executefetchrequest:fetchrequest Error:nil];
    • Use Nspredicate to screen students with a score higher than 90

Nspredicate *predicate = [nspredicate predicatewithformat:@ "Score >="];fetchrequest.predicate = predicate;
Advanced

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;// Asynchronous Request nsasynchronousfetchrequest *asyncrequst = [[nsasynchronousfetchrequest alloc]  initwithfetchrequest:fetchrequest completionblock:^ (Nsasynchronousfetchresult *result)  {     for  (Nsobject *obj in result.finalresult)  {         nslog (@ "%@",  [obj valueforkey:@ "score"]);     }}];// Executes an asynchronous request [context executerequest:asyncrequst error:nil];

Note:   When using an asynchronous request, you need to set the concurrency type of the Nsmanagedcontext object, otherwise an error occurs.

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

The workaround is to set the concurrency type of the context object when it is created.

Nspersistentstorecoordinator *coordinator = [self persistentstorecoordinator];if (!coordinator) {return nil;} Create a context object and set the concurrency type _managedobjectcontext = [[Nsmanagedobjectcontext alloc] Initwithconcurrencytype: Nsmainqueueconcurrencytype]; [_managedobjectcontext Setpersistentstorecoordinator:coordinator];
Resources
    1. Core Data Asynchronous operation: http://code.tutsplus.com/tutorials/ios-8-core-data-and-asynchronous-fetching--cms-22241

    2. Core Data concurrency operation: http://code.tutsplus.com/tutorials/core-data-from-scratch-concurrency--cms-22131

    3. Bulk update of core data:http://code.tutsplus.com/tutorials/ios-8-core-data-and-batch-updates--cms-22164

This document is organized by the Changsha Camp David Education .


This article is from the "Camp David Education" blog, so be sure to keep this source http://diveinedu.blog.51cto.com/3029331/1617604

CoreData Third Lesson data query

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.