Core Data主要是ios的一个模型,不是数据库,主要是作为数据管理,对象存储,对象读取恢复的功能提供支持的系统,可以使用SQL作为存储设备,但是本身不是一个数据库。
CoreData包含的框架有:
1。Managed Objects and Context 管理器,所有的数据都是通过该管理进行读取和存储。NSManagedObjectContext
2。Entity Description 实体描述,这个是获取数据库某个表单的实体 NSEntityDescription 主要包含两个重要的属性:名称和类名
3。Fetch Requests 数据请求要求,设置搜索条件,请求数据 NSFetchRequest
4。Managed Object Models 该方法描述了实体的名称及其属性,和表单的表单字段以及类型对应起来。可以在完成表单后通过操作xcode自动生成。
在coredata操作过程中我们主要接触的对象类型有上面几种,还有数据持久化存储助理(presistent Store Coordinator),持久化存储(Persistent Stores),持久化文档(Persistent Documents)等对象,这些都是在读取文件的时候会对其进行操作,这里暂不表。
1。创建一个CoreData模型。
A.在Frameworks里面引入CoreData.framework
B.在File->New->CoreData->DataModel->输入名字Data 生成成功,点开如下图
C.如图,在右边点开属性的CoreData Model的identifier输入1.0.0
D.如图,添加Add Entity 创建表单的模型,这个地方创建生成后,如何我们选择的是SQL,则一个Entity则是对应一个表单。
生成后如图:
点击Editor->Create NSManage Object Subclass 则将我们创建的表单生成一个以该表单命名的PersonInfo的类。该类方便操作coreData的时候进行直观赋值。
到目前位置,配置的的文件和设置已经完成,接下来主要的任务就是通过代码对数据集合进行操作。
2.代码读取数据库内容
在appdelegate里面,添加以下代码,将数据库从sql里面缓存到managedObjectContext
.h文件
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
.m文件
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataTest" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataTest.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
这部分的代码其实在我们创建项目的时候,如果勾选了use coreData 则自动生成。
3.对表单进行操作
4.CoreData如何实现版本的升级
随着我们的使用,有很多时候我们在更新软件版本的时候会对数据库某个字段进行修改,或者添加,删除操作,如果没有对coreData进行升级处理,则当我们对数据库进行修改的时候,已有的用户操作过程常常出现异常现象。需要删除软件重新下载软件才能去除异常。处理的步骤主要是:
A.在以上代码的- (NSPersistentStoreCoordinator *)persistentStoreCoordinator方法中
修改为
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataTest.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary* options=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&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.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
里面的
NSDictionary* options=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
则是代表着改数据库可以升级。
B。点击CoreDataTest.xcdatamodeld然后点击菜单栏的Editor里面的add model verson 则可以给数据库创建版本。base on model指的是我们更新的上一个版本是哪一个。创建完成后可以看到在CoreDataTest.xcdatamodeld如一下已经有两个模板的数据库版本。
然后点击CoreDataTest.xcdatamodeld的属性,设置Versioned core data model的current为coreDataTest1.0则可以了。完成后可以看到绿色的勾打在CoreDataTest1.0上面。然后我们选中CoreDataTest1.0.xcdatamodel对各个表单进行修改即可。修改之后也对应地重新生成nsmanagedobject model subclass即可。
这样完成后我们就可以对数据库进行读写等操作而不会有影响了。