您的位置:首页 > 数据库

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

2015-09-21 23:11 537 查看
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 Model,Persistent Store Coordinator,Managed Object Context ,并且自动封装了大量的sqlite的函数方法。
3、在attributes选项处添加该实体对象的属性。
4、选中该实体类,在模拟器选项上点击Editor下的create Managed Object Context subclass..创建Managed Object Context的子类。
5、这个子类中,编译器自动生成了所添加的所有属性。
6、在应用程序代理类中用代码对数据库进行操作。

创建实体对象(设置类名为Person)截图如下:      添加其属性截图如下:



所有产生的文件截图如下:           创建的数据库表视图如下:





具体代码如下:
AppDelegate.h(自动生成的代码)

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

@end


AppDelegate.m(自动生成的代码,封装的是sqlite的一些函数方法)

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
// 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.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
// 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.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreData___" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}

// Create the coordinator and store

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData___.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// 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.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}

return _persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// 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.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}


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

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface Person : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) NSNumber * gender;

@end


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

#import "Person.h"

@implementation Person

@dynamic name;
@dynamic age;
@dynamic gender;

@end


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

在AppDelegate.m文件中进行:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//创建实体对象
Person *person = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Person class]) inManagedObjectContext:self.managedObjectContext];

//设置实体对象的属性
person.name = @"zhangsan";
person.age = @20;
person.gender = @'M';

//保存数据
[self saveContext];

//查询实体对象的数据
//1.创建请求对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([person class])];
//2.创建排序对象
NSSortDescriptor *ageSort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
//3.发出请求
[request setSortDescriptors:@[ageSort]];
//4.执行查询
NSError *error = nil;
NSArray *persons = [self.managedObjectContext executeFetchRequest:request error:&error];
if(!error)
{
//遍历所有的实体对象
[persons enumerateObjectsUsingBlock:^(Person *person, NSUInteger idx, BOOL *stop) {
NSLog(@"name:%@,age:%@,gender:%c",person.name,person.age,(char)[person.gender integerValue]);

//修改对象
person.age = @([person.age integerValue] + 2);

//删除对象
if(idx == 2)
{
[self.managedObjectContext deleteObject:person];
NSError *error = nil;
[self.managedObjectContext save:&error];
if([person isDeleted])
{
NSLog(@"删除成功");
}
}
}];
}

//保存上下文
[self saveContext];

return YES;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: