CoreData的增删改查

首先使用CoreData创建Demo,勾上CoreData选项

             

然后创建Entity对象,点击Add Entity(+)按钮

生成Entity对象

                

重命名双击Entity选项,然后输入Person

        

设置Person属性,点击Attributes选项中的+号,实现添加属性,并给属性命名,且添加属性相关的类型

然后command+N,创建NSManagedObject subclass

然后点击Next

然后勾上 CoreData_Demo选项,然再点击Next

   

接着勾上Person选项,再次点击Next

   

接下来,跟着系统的提示进行操作,最后生成Person类

   

下面是相关操作的代码

    AppDelegate.h头文件的代码

 1 #import <UIKit/UIKit.h>
 2 #import <CoreData/CoreData.h>
 3 
 4 @interface AppDelegate : UIResponder <UIApplicationDelegate>
 5 
 6 @property (strong, nonatomic) UIWindow *window;
 7 
 8 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
 9 @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
10 @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
11 
12 - (void)saveContext;
13 - (NSURL *)applicationDocumentsDirectory;
14 
15 
16 @end

      AppDelegate.h实现文件的代码

  1 #import "AppDelegate.h"
  2 #import "RootViewController.h"
  3 @interface AppDelegate ()
  4 
  5 @end
  6 
  7 @implementation AppDelegate
  8 
  9 
 10 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 11     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
 12     // Override point for customization after application launch.
 13     self.window.backgroundColor = [UIColor whiteColor];
 14     
 15     self.window.rootViewController = [[RootViewController alloc] init];
 16     
 17     [self.window makeKeyAndVisible];
 18     return YES;
 19 }
 20 
 21 
 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 "com.YXYC.Test_CoreData_Test" 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:@"Test_CoreData_Test" 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 return 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:@"Test_CoreData_Test.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] init];
 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

  RootViewController.h头文件相关的代码

1 #import <UIKit/UIKit.h>
2 
3 @interface RootViewController : UIViewController
4 
5 @end

  RootViewController.h实现文件相关的代码

  1 #import "RootViewController.h"
  2 #import "AppDelegate.h"
  3 @interface RootViewController ()
  4 
  5 @property (strong, nonatomic) AppDelegate *appDelegate;
  6 
  7 @end
  8 
  9 @implementation RootViewController
 10 
 11 - (void)viewDidLoad {
 12     [super viewDidLoad];
 13     self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
 14     // 存储数据
 15     [self saveData];
 16     // 查询全部数据
 17     [self readData];
 18     NSMutableArray *datas = [[NSMutableArray alloc] init];
 19     // 得到查询的结果(条件查询)
 20     datas = [self getObjectsWithPredicate];
 21     // 删除
 22     [self removeObjects];
 23     // 修改
 24     [self changeObjects];
 25 }
 26 
 27 /**
 28  *  存储数据
 29  */
 30 - (void)saveData
 31 {
 32     NSManagedObjectContext *object = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.appDelegate.managedObjectContext];
 33     [object setValue:@"GL" forKey:@"name"];
 34     [object setValue:@"female" forKey:@"sex"];
 35     
 36 }
 37 
 38 /**
 39  *  查询全部数据
 40  */
 41 - (void)readData
 42 {
 43     // 实例化一个查询(Fetch)请求
 44     NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
 45     NSEntityDescription *object = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appDelegate.managedObjectContext];
 46     [fetch setEntity:object];
 47     
 48     NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
 49     NSLog(@"sort:%@",sort);
 50     
 51     NSArray *sortarr = [[NSArray alloc] initWithObjects:sort, nil];
 52     [fetch setSortDescriptors:sortarr];
 53     
 54     NSError *error = nil;
 55     // 让_context执行查询数据
 56     NSArray *fetchresult = [self.appDelegate.managedObjectContext executeFetchRequest:fetch error:&error];
 57     
 58     for (NSManagedObject *object in fetchresult) {
 59         NSLog(@"name:%@==sex:%@",[object valueForKey:@"name"],[object valueForKey:@"sex"]);
 60     }
 61     
 62 }
 63 /**
 64  *  条件查询
 65  *
 66  *  @return 查询结果的Entity数组
 67  */
 68 - (NSMutableArray *)getObjectsWithPredicate
 69 {
 70     NSError *error = nil;
 71     // 实例化一个查询(Fetch)请求
 72     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
 73     // 条件查询
 74     request.predicate = [NSPredicate predicateWithFormat:@"sex LIKE '*female'"];
 75     // 让_context执行查询数据
 76     NSArray *array = [self.appDelegate.managedObjectContext executeFetchRequest:request error:&error];
 77     return [NSMutableArray arrayWithArray:array];
 78 }
 79 /**
 80  *  删除操作
 81  */
 82 - (void)removeObjects
 83 {
 84     NSError *error = nil;
 85     // 实例化查询请求
 86     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
 87     // 设置条件
 88     request.predicate = [NSPredicate predicateWithFormat:@"name = 'LF'"];
 89     // 由上下文查询数据
 90     NSArray *result =[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error];
 91     // 打印条件结果,并删除对象
 92     for (NSManagedObject *object in result) {
 93         // 删除对象
 94         [self.appDelegate.managedObjectContext deleteObject:object];
 95     }
 96     // 删除后,保存数据
 97     [self.appDelegate.managedObjectContext save:&error];
 98 }
 99 /**
100  *  修改
101  */
102 - (void)changeObjects
103 {
104     NSError *error = nil;
105     // 实例化查询请求
106     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
107     // 设置条件
108     request.predicate = [NSPredicate predicateWithFormat:@"name = 'GL'"];
109     // 由上下文查询数据
110     NSArray *result =[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error];
111     // 修改对象
112     for (NSManagedObject *object in result) {
113         // 修改对象
114         [object setValue:@"GYL" forKey:@"name"];
115     }
116     // 修改后,保存数据
117     [self.appDelegate.managedObjectContext save:&error];
118 }
119 
120 @end
 
 
原文地址:https://www.cnblogs.com/lantu1989/p/4698738.html