CoreData简单使用流程分析

来源:互联网 发布:25转行做程序员 编辑:程序博客网 时间:2024/05/14 02:02

第一步:将工程中得所有实体类模型文件【Xxx.xcdatamodeld文件】读入内存,并使用一个NSManagedObjectModel单例对象在内存中保存.

  1. 读入工程中所有的实体类模型文件【以单例对象保存】
 1. (instancetype)managedObjectModel {    static NSManagedObjectModel *model = nil;    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        //搜索工程中所有的.xcdatamodeld文件,并加载所有的实体到一个NSManagedObjectModel对象中        model = [NSManagedObjectModel mergedModelFromBundles:@[[NSBundle mainBundle]]];    });    return model;}
  1. 只读入某个名字的模型文件【同样以单例对象保存】
+ (instancetype)managedObjectModelWithName:(NSString *)modelName {    static NSManagedObjectModel *model = nil;    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        /*初始化必须依赖.momd文件路径,而.momd文件由.xcdatamodeld文件编译而来*/        NSURL *modelURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];        model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    });    return model;}

第二步:利用实体类模型文件的对象NSManagedObjectModel对象,创建NSPersistentStoreCoordinator数据存储区域的单例对象

/** *  创建NSPersistentStoreCoordinator对象【单例保存】 * *  @param isAuto    是否使用自动版本迁移 *  @param storeType 数据文件在手机沙盒目录存放的格式 *  @param fileURL   数据文件在手机沙盒目录存放的路径 * */+ (instancetype)createWithAutoMigration:(BOOL)isAuto                              StoreType:(NSString *)storeType                           StoreFileURL:(NSURL *)fileURL{    //1. 实体类模型文件读入内存对象保存    NSManagedObjectModel *model = [NSManagedObjectModel managedObjectModel];    //2. 传入实体类模型文件对象,创建PersistentStoreCoordinator存储区域对象    NSPersistentStoreCoordinator * coordinator = nil;    coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];    //3. 指定在手机本地存放数据库的 位置、类型、配置    NSDictionary *options = isAuto ? [self autoMigrationOptions] : nil;    NSError *error = nil;    [coordinator addPersistentStoreWithType:storeType                              configuration:nil                                        URL:fileURL                                    options:options                                      error:&error];    if (error) {        ErrorLog(error);        abort();    }    if (!coordinator) {        [NSException raise:@"NSPersistentCoordinator Create Failed With URL: %@ , Error Message: %@"                    format:[fileURL absoluteString], [error localizedDescription]];    }    return coordinator;}

第三步:使用数据存储区域对象NSPersistentCoordinator单例对象,创建NSManagedObjectContext对象,使用这个对象作为操作数据持久化Api的入口

  1. NSManagedObjectContext在多线程上得使用
//1. 主线程上得单例Context对象+ (instancetype)foregroundContext {    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _foregoundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];        //默认设置一个版本自动迁移的存储器        id persistentStoreCoordinator = [NSPersistentStoreCoordinator coordinatorUseAutoMigration];        [_foregoundContext setPersistentStoreCoordinator:persistentStoreCoordinator];    });    return _foregoundContext;}
//2. 后台子线程上得单例Context对象+ (instancetype)backgroundContext {    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        id context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];        [self setBackgroudContext:context];        [_backgoundContext setParentContext:[self foregroundContext]];    });    return _backgoundContext;}
//3. 提供获取单例Context对象的入口函数,对不同线程提供不同的单例Context对象+ (instancetype)managedObjectContext {    if ([NSThread isMainThread]) {        return [self foregroundContext];    } else {        return [self backgroundContext];    }}

最后,CoreData自动将实体类模型文件、已经实体类之间的关系,在手机沙盒目录Document目录创建数据库表,并设置表之间的关联关系。

0 0
原创粉丝点击