关于Core Data的一些整理(一)

关于Core Data的一些整理(一)

在Xcode7.2中只有Mast-Debug和Single View中可以勾选Use Core Data

如果勾选了Use Core Data,Xcode会自动在AppDelegate中帮你生成Core Data的核心代码,并且自动生成.xcdatamodeld数据文件
 
  1 //Appdelegate.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) NSManagedObjectContext *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.m中系统帮助生成的代码
 22 - (void)applicationWillTerminate:(UIApplication *)application {
 23   // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
 24   // Saves changes 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     // The directory the application uses to store the Core Data store file. This code uses a directory named "qq100858433.JMHitList" in the application's documents directory.
 36     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
 37 }
 38 
 39 - (NSManagedObjectModel *)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 implementation 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 = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
 58     NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"JMHitList.sqlite"];
 59     NSError *error = nil;
 60     NSString *failureReason = @"There was an 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[NSLocalizedFailureReasonErrorKey] = failureReason;
 66         dict[NSUnderlyingErrorKey] = 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 should not use this function in a shipping application, although it may be useful during development.
 70         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
 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] initWithConcurrencyType:NSMainQueueConcurrencyType];
 89     [_managedObjectContext setPersistentStoreCoordinator:coordinator];
 90     return _managedObjectContext;
 91 }
 92 
 93 #pragma mark - Core Data Saving support
 94 
 95 - (void)saveContext {
 96     NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
 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 should 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

假如你在.xcdatamodeld中生成了如下实体和实体属性:

 

那么在VC中获取数据库内容和添加数据库内容的代码如下:
 1   //从Core Data中获得已有数据
 2   id appDelegate = [UIApplication sharedApplication].delegate;
 3   NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
 4   NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
 5   @try {
 6     self.people = [NSMutableArray arrayWithArray:[managedContext executeFetchRequest:fetchRequest error:nil]];
 7   }
 8   @catch (NSException *exception) {
 9     NSLog(@"Could not fetch %@", [exception userInfo]);
10   }
11   @finally {
12     NSLog(@"Fetch Successful");
13   }
14   
15   //为数据库添加实体实例
16   id appDelegate = [UIApplication sharedApplication].delegate;
17   //NSManagedObjectContext可以看做内存中用来处理managedObjects的暂存器
18   NSManagedObjectContext *mangedContext = [appDelegate managedObjectContext];
19   //下面两种方法都可以获得Person实体
20 //  NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:mangedContext];
21 //  NSManagedObject *person = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:mangedContext];
22 //  [person setValue:name forKey:@"name"];
23   NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:mangedContext];
24   [person setValue:name forKey:@"name"];
25   @try {
26     [mangedContext save:nil];
27     [self.people addObject:person];
28   }
29   @catch (NSException *exception) {
30     NSLog(@"Could not save %@", [exception userInfo]);
31   }
32   @finally {
33     NSLog(@"Save Successfullt!");
34   }

 

 
 
 
posted @ 2016-01-14 17:32  jackma86  阅读(375)  评论(0编辑  收藏  举报