Core Data sorting (1): coredata sorting

Source: Internet
Author: User

Core Data sorting (1): coredata sorting
Sorting Core Data (1)

In Xcode7.2, only the Use Core Data option can be selected in Mast-Debug and Single View.

If you select Use Core Data, Xcode will automatically generate the Core code of Core Data in AppDelegate and automatically generate .xcdatamodeldData Files
1 // Appdelegate. in h, 2 # import <UIKit/UIKit. h> 3 # import <CoreData/CoreData. h> 4 5 @ interface AppDelegate: UIResponder <UIApplicationDelegate> 6 7 @ property (strong, nonatomic) UIWindow * window; 8 9 @ property (readonly, strong, nonatomic) implements * managedObjectContext; 10 @ property (readonly, strong, nonatomic) NSManagedObjectModel * managedObjectModel; 11 @ property (readonly, strong, Nonatomic) NSPersistentStoreCoordinator * persistentStoreCoordinator; 12 13-(void) saveContext; 14-(NSURL *) applicationDocumentsDirectory; 15 16 17 @ end 18 19 20 21 // Appdelegate. the Code 22-(void) applicationWillTerminate :( UIApplication *) application {23 // Called when the application is about to terminate. save data if appropriate. see also applicationDidEnterBackground :. 24 // Saves chan Ges in the application's managed object context before the application terminates. 25 [self saveContext]; 26} 27 28 # pragma mark-Core Data stack 29 30 @ synthesize managedObjectContext = _ managedObjectContext; 31 @ synthesize managedObjectModel = _ managedObjectModel; 32 @ synthesize persistentStoreCoordinator = _ persistentStoreCoordinator; 33 34-(NSURL *) applicationDocumentsDirectory {35 // Directory the application uses to store the Core Data store file. this code uses a directory named "qq100858433.JMHitList" in the application's named ents directory. 36 return [[NSFileManager defaultManager] URLsForDirectory: NSDocumentDirectory inDomains: NSUserDomainMask] lastObject]; 37} 38 39-(optional *) managedObjectModel {40 // The managed object model for the application. it Is a fatal error for the application not to be able to find and load its model. 41 if (_ managedObjectModel! = Nil) {42 return _ managedObjectModel; 43} 44 NSURL * modelURL = [[NSBundle mainBundle] URLForResource: @ "JMHitList" withExtension: @ "momd"]; 45 _ managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL: modelURL]; 46 return _ managedObjectModel; 47} 48 49-(NSPersistentStoreCoordinator *) persistentStoreCoordinator {50 // The persistent store coordinator for the application. this im Plementation creates and returns a coordinator, having added the store for the application to it. 51 if (_ persistentStoreCoordinator! = Nil) {52 return _ persistentStoreCoordinator; 53} 54 55 // Create the coordinator and store 56 57 _ persistentStoreCoordinator = [[using alloc] Using: [self managedObjectModel]; 58 NSURL * storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent: @ "JMHitList. sqlite "]; 59 NSError * error = nil; 60 NSString * failureReason = @" There was Error creating or loading the application's saved data. "; 61 if (! [_ PersistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: storeURL options: nil error: & error]) {62 // Report any error we got. 63 NSMutableDictionary * dict = [NSMutableDictionary dictionary]; 64 dict [NSLocalizedDescriptionKey] = @ "Failed to initialize the application's saved data"; 65 dict [partition] = failureReason; 66 dict [NSUnderlyingE RrorKey] = error; 67 error = [NSError errorWithDomain: @ "YOUR_ERROR_DOMAIN" code: 9999 userInfo: dict]; 68 // Replace this with code to handle the error appropriately. 69 // abort () causes the application to generate a crash log and terminate. you shoshould not use this function in a shipping application, although it may be useful during development. 70 NSLog (@ "Unresolved error % @, % @", error, [error us ErInfo]); 71 abort (); 72} 73 74 return _ persistentStoreCoordinator; 75} 76 77 78-(NSManagedObjectContext *) managedObjectContext {79 // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application .) 80 if (_ managedObjectContext! = Nil) {81 return _ managedObjectContext; 82} 83 84 NSPersistentStoreCoordinator * coordinator = [self persistentStoreCoordinator]; 85 if (! Coordinator) {86 return nil; 87} 88 _ managedObjectContext = [[NSManagedObjectContext alloc] handler: Handler]; 89 [_ managedObjectContext handler: coordinator]; 90 return _ managedObjectContext; 91} 92 93 # pragma mark-Core Data Saving support 94 95-(void) saveContext {96 NSManagedObjectContext * managedObjectContext = self. managedObjectCont Ext; 97 if (managedObjectContext! = Nil) {98 NSError * error = nil; 99 if ([managedObjectContext hasChanges] &! [ManagedObjectContext save: & error]) {100 // Replace this implementation with code to handle the error appropriately.101 // abort () causes the application to generate a crash log and terminate. you shoshould not use this function in a shipping application, although it may be useful during development.102 NSLog (@ "Unresolved error % @, % @", error, [error userInfo]); 103 abort (); 104} 105} 106} 107 108 @ end

Assume that you are.xcdatamodeldThe following entity and entity attributes are generated:

 

The code for obtaining the database content and adding the database content in VC is as follows:
1 // obtain the existing Data from the Core Data. 2 id appDelegate = [UIApplication sharedApplication]. delegate; 3 NSManagedObjectContext * managedContext = [appDelegate managedObjectContext]; 4 NSFetchRequest * fetchRequest = [NSFetchRequest response: @ "Person"]; 5 @ try {6 self. people = [NSMutableArray arrayWithArray: [managedContext executeFetchRequest: fetchRequest error: nil]; 7} 8 @ catch (NSException * exce Ption) {9 NSLog (@ "cocould not fetch % @", [exception userInfo]); 10} 11 @ finally {12 NSLog (@ "Fetch Successful "); 13} 14 15 // Add the entity instance for the database 16 id appDelegate = [UIApplication sharedApplication]. delegate; 17 // NSManagedObjectContext can be viewed as the memory for processing managedObjects. 18 NSManagedObjectContext * mangedContext = [appDelegate managedObjectContext]; 19 // both of the following methods can obtain the Person object 20 // NSEntityDescription * entity = [NSEntityDes Cription entityForName: @ "Person" identifier: mangedContext]; 21 // NSManagedObject * person = [[NSManagedObject alloc] initWithEntity: entity identifier: mangedContext]; 22/[person setValue: name forKey: @ "name"]; 23 NSManagedObject * person = [NSEntityDescription insertNewObjectForEntityForName: @ "Person" inManagedObjectContext: mangedContext]; 24 [person setValue: name forKe Y: @ "name"]; 25 @ try {26 [mangedContext save: nil]; 27 [self. people addObject: person]; 28} 29 @ catch (NSException * exception) {30 NSLog (@ "cocould not save % @", [exception userInfo]); 31} 32 @ finally {33 NSLog (@ "Save Successfullt! "); 34}

 

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.