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=[NsfetchrequestFetchrequestwithentityname:@ "person" ]; or nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init< Span class= "P" >; nsentitydescription *entity = [< Span class= "BP" >nsentitydescription entityforname:@ "person" Span class= "NL" >inmanagedobjectcontext:context]; Fetchrequest. Entity = entity
- Created through the request template created in the model file.
//使用managedModel获取fetchRequest模版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"]; //如果需要改变结果的类型,不能使用从模版生成的request对象 NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; //获取结果总数 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"];//获取结果数目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=[NsfetchrequestFetchrequestwithentityname:@ "Person"];Sort descriptor, sorted in descending order of scoreNssortdescriptor*sort01=[NssortdescriptorSortdescriptorwithkey:@ "Score"Ascending:NO];You can sort by multiple attributes at the same timeFetchrequest.Sortdescriptors=@[sort01];Nsarray*Result=[ContextExecutefetchrequest:FetchrequestError:nilif (result) {_ People = [nsmutablearray arraywitharray :resultfor (nsobject *obj in _people) {nslog (@ "%@" [obj Valueforkey:@ "score" ); }} /span>
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=[NsfetchrequestFetchrequestwithentityname:@ "Person"];Nssortdescriptor*sort01=[NssortdescriptorSortdescriptorwithkey:@ "score" ascending:NO ; fetchrequest. Sortdescriptors = @[sort01];< Span class= "C1" >//limit only take the first 10, in fact, this is problematic, in case there are duplicate 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 >= 90"];fetchRequest.predicate = predicate;
Advanced
The above data acquisition methods are synchronous, if the amount of data is large, it will significantly affect the performance of the program and the user experience. The asynchronous Data acquisition feature is also available in Core data.
Appdelegate*Appdelegate=(Appdelegate*)[UIApplicationSharedapplication].Delegate;Nsmanagedobjectcontext*Context=Appdelegate.Managedobjectcontext;Nsfetchrequest*Fetchrequest=[NsfetchrequestFetchrequestwithentityname:@ "Person"];Nssortdescriptor*sort01=[NssortdescriptorSortdescriptorwithkey:@ "Score"Ascending:NO];Fetchrequest.Sortdescriptors=@[sort01];Fetchrequest.Fetchlimit=2;Asynchronous requestNsasynchronousfetchrequest*Asyncrequst=[[NsasynchronousfetchrequestAlloc]Initwithfetchrequest:FetchrequestCompletionblock:^(Nsasynchronousfetchresult*result) {for (*obj in result. Finalresult) {nslog (@ "%@" [obj valueforkey:@ " Score "]); }}]; //execute asynchronous request [context executerequest :asyncrequst error:nil ;
Note: When using asynchronous requests, 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
- Core Data Asynchronous Operation: http://code.tutsplus.com/tutorials/ios-8-core-data-and-asynchronous-fetching--cms-22241
- Core data concurrency operation: http://code.tutsplus.com/tutorials/core-data-from-scratch-concurrency--cms-22131
- Bulk Update 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 .
CoreData Third Lesson data query