iOS:CoreData数据库的使用一(创建单个数据库表)

CoreData数据库框架:mac系统自带的数据库,它是苹果公司对sqlite进行封装而来的,既提供了对数据库的主要操作,也提供了具体的视图关系模型。

需要用到三个对象:
1•Managed Object Model(被管理对象模型): 
        数据库的轮廓,或者结构。包含了各个实体的定义信息
2•Persistent Store Coordinator (持久性数据协调器):
        数据库连接库,在这里设置数据存储的名字和位置,以及数据存储的时机
3•Managed Object Context (被管理对象上下文):
                数据的实际内容,基本上,插入数据,查询数据,删除数据的工作都在这里完成
 
三者关系图显示:
        
 
 
 
•Persistent store     //持久化存储
•Persistent store coordinator    //持久化存储协调器
•Managed object model (MOM)    //被管理对象的数据模型(对实例对象进行描述)
•Managed object    //被管理对象
•Managed object context (MOC) //被管理的实例对象
 
使用步骤如下:
1、创建项目时,勾选CoreData选项。
2、此时项目文件中多了一个CoreData___.xcdatamodel文件,选中该文件,进入其创建数据库表格界面,在界面的左下角点击Add Entity添加实体对象,并设置该对象的类名;与此同时,在AppDeletegate类中,自动声明和定义了需要的三个对象Managed Object ModelPersistent Store CoordinatorManaged Object Context ,并且自动封装了大量的sqlite的函数方法。
3、在attributes选项处添加该实体对象的属性。
4、选中该实体类,在模拟器选项上点击Editor下的create Managed Object Context subclass..创建Managed Object Context的子类。
5、这个子类中,编译器自动生成了所添加的所有属性。
6、在应用程序代理类中用代码对数据库进行操作。
 
创建实体对象(设置类名为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.m(自动生成的代码,封装的是sqlite的一些函数方法)

 1 #pragma mark - Core Data stack
 2 
 3 @synthesize managedObjectContext = _managedObjectContext;
 4 @synthesize managedObjectModel = _managedObjectModel;
 5 @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
 6 
 7 - (NSURL *)applicationDocumentsDirectory {
 8     // The directory the application uses to store the Core Data store file. This code uses a directory named "com.bjsxt.CoreData___" in the application's documents directory.
 9     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
10 }
11 
12 - (NSManagedObjectModel *)managedObjectModel {
13     // 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.
14     if (_managedObjectModel != nil) {
15         return _managedObjectModel;
16     }
17     NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreData___" withExtension:@"momd"];
18     _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
19     return _managedObjectModel;
20 }
21 
22 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
23     // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
24     if (_persistentStoreCoordinator != nil) {
25         return _persistentStoreCoordinator;
26     }
27     
28     // Create the coordinator and store
29     
30     _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
31     NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData___.sqlite"];
32     NSError *error = nil;
33     NSString *failureReason = @"There was an error creating or loading the application's saved data.";
34     if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
35         // Report any error we got.
36         NSMutableDictionary *dict = [NSMutableDictionary dictionary];
37         dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
38         dict[NSLocalizedFailureReasonErrorKey] = failureReason;
39         dict[NSUnderlyingErrorKey] = error;
40         error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
41         // Replace this with code to handle the error appropriately.
42         // 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.
43         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
44         abort();
45     }
46     
47     return _persistentStoreCoordinator;
48 }
49 
50 
51 - (NSManagedObjectContext *)managedObjectContext {
52     // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
53     if (_managedObjectContext != nil) {
54         return _managedObjectContext;
55     }
56     
57     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
58     if (!coordinator) {
59         return nil;
60     }
61     _managedObjectContext = [[NSManagedObjectContext alloc] init];
62     [_managedObjectContext setPersistentStoreCoordinator:coordinator];
63     return _managedObjectContext;
64 }
65 
66 #pragma mark - Core Data Saving support
67 
68 - (void)saveContext {
69     NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
70     if (managedObjectContext != nil) {
71         NSError *error = nil;
72         if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
73             // Replace this implementation with code to handle the error appropriately.
74             // 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.
75             NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
76             abort();
77         }
78     }
79 }

Person.h(自动生成的代码)

 1 #import <Foundation/Foundation.h>
 2 #import <CoreData/CoreData.h>
 3 
 4 
 5 @interface Person : NSManagedObject
 6 
 7 @property (nonatomic, retain) NSString * name;
 8 @property (nonatomic, retain) NSNumber * age;
 9 @property (nonatomic, retain) NSNumber * gender;
10 
11 @end

Person.m(自动生成的代码)

 1 #import "Person.h"
 2 
 3 
 4 @implementation Person
 5 
 6 @dynamic name;
 7 @dynamic age;
 8 @dynamic gender;
 9 
10 @end

重点来了,对数据库进行的主要操作,需要人为代码写的:

在AppDelegate.m文件中进行:

 1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 2     
 3     //创建实体对象
 4     Person *person = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Person class]) inManagedObjectContext:self.managedObjectContext];
 5     
 6     //设置实体对象的属性
 7     person.name = @"zhangsan";
 8     person.age = @20;
 9     person.gender = @'M';
10     
11     //保存数据
12     [self saveContext];
13     
14     
15     //查询实体对象的数据
16     //1.创建请求对象
17     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([person class])];
18     //2.创建排序对象
19     NSSortDescriptor *ageSort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
20     //3.发出请求
21     [request setSortDescriptors:@[ageSort]];
22     //4.执行查询
23     NSError *error = nil;
24     NSArray *persons = [self.managedObjectContext executeFetchRequest:request error:&error];
25     if(!error)
26     {
27         //遍历所有的实体对象
28         [persons enumerateObjectsUsingBlock:^(Person *person, NSUInteger idx, BOOL *stop) {
29             NSLog(@"name:%@,age:%@,gender:%c",person.name,person.age,(char)[person.gender integerValue]);
30             
31             //修改对象
32             person.age = @([person.age integerValue] + 2);
33             
34             
35             //删除对象
36             if(idx == 2)
37             {
38                 [self.managedObjectContext deleteObject:person];
39                 NSError *error = nil;
40                 [self.managedObjectContext save:&error];
41                 if([person isDeleted])
42                 {
43                     NSLog(@"删除成功");
44                 }
45             }
46         }];
47     }
48     
49     //保存上下文
50     [self saveContext];
51     
52     return YES;
53 }

 

posted @ 2015-09-21 23:11  XYQ全哥  阅读(550)  评论(0编辑  收藏  举报