首页 > 代码库 > IOS中数据持久化1-CoreData

IOS中数据持久化1-CoreData

CodeData是苹果提供的关系数据库下面是其他博主总结的部分内容(当初拷贝的时候忘了拷贝链接):

托管对象(managed object):一个托管对象代表你想要保存到数据存储中的一个对象
托管对象上下文(managed object context):托管对象上下文类似于应用程序和数据存储之间的一块缓冲区。这块缓冲区包含所有未被写入数据存储的托管对象。你可以添加、删除、更改缓冲区内的托管对象。在很多时候,当你需要读、插入、删除对象时,你将会调用托管对象上下文的方法。
持久化存储协调器(persistent store coordinator):持久化存储协调器处理到数据存储的连接,并且包含一些底层信息,像用到数据存储的名字和位置。这个类通常被托管对象上下文用到。
托管对象模型(managed object model):托管对象模型是一个类,这个类包含每一个你想存储到数据存储中的托管对象的定义。

使用CoreData

1 .在你可以读或写模型对象到当前数据存储之前,你需要实例化托管对象模型、托管对象上下文、持久化存储协调器。
托管对象模型由NSManagedObjectModel类的一个实例表示。在一个工程中我们只需要为所有的.xcdatamodeld文件实例化一个对象。
NSManagedObjectModel* managedObjectModel = [NSManagedObjectModel
        mergedModelFromBundles:nil];
mergedModelFromBundles: 搜索工程中所有的.xcdatamodeld文件,并加载所有的实体到一个NSManagedObjectModel  实例中。
这样托管对象模型知道所有当前工程中用到的托管对象的定义

2 有了托管对象模型实例之后,我们就可以创建一个持久化协调器实例了。持久化协调器处理到数据存储的连接。大概是处理怎么把对象写到数据存储或怎么从数据存储读对象吧。

有了持久化协调器实例之后,我们需要提供一个数据存储给它管理。你可以通过发送addPersistentStoreWithType:configuration:URL:options:error:消息来实现。

最后一步就是实例化托管对象上下文。有了托管对象上下文,你就可以方便的管理对象了。
 
如何获取appdelegat中得托管对象上下文,持久化协调器,托管对象模型:
 
下面是使用时的个人经验:

 

总结:

NSManagedObjectModel:实例化托管对象在appdeletage中已经使用且仅仅使为了创建持久化存储协调器persistentStoreCoordinator服务得,实际使用时并没有直接操作该对象:
persistentStoreCoordinator:为了创建数据存储的链接而生,实际操作时并没有直接使用该对象
所以在实际使用时用的是托管对象上下文


添加数据过程:
      1.创建实体数据描述 NSEntityDescription
       2.根据描述文件创建实例对象
       3.保存

在创建程序时,勾上coreData后Appdelegate就自动为我们创建了如下三个属性

@synthesize managedObjectContext = _managedObjectContext;

@synthesize managedObjectModel = _managedObjectModel;

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

并且自动为我们实现了下面四个方法:

- (void)saveContext{    NSError *error = nil;    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;    if (managedObjectContext != 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();        }     }}#pragma mark - Core Data stack// 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:@"Core_Data" 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:@"Core_Data.sqlite"];        NSError *error = nil;    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} 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];}

 

IOS中数据持久化1-CoreData