CoreData簡單使用流程分析

  1. 將工程中得全部實體類模型文件【Xxx.xcdatamodeld文件】讀入內存,並使用一個NSManagedObjectModel單例對象在內存中保存.
//方式1、 讀入工程中全部的實體類模型文件【以單例對象保存】

+ (instancetype)managedObjectModel {
    static NSManagedObjectModel *model = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //搜索工程中全部的.xcdatamodeld文件,並加載全部的實體到一個NSManagedObjectModel對象中
        model = [NSManagedObjectModel mergedModelFromBundles:@[[NSBundle mainBundle]]];
    });
    return model;
}

//方式2、 只讀入某個名字的模型文件【一樣以單例對象保存】

+ (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;
}
  1. 利用實體類模型文件的對象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;
}
  1. 使用數據存儲區域對象NSPersistentCoordinator單例對象,建立NSManagedObjectContext對象,使用這個對象做爲操做數據持久化Api的入口
//類型一、 主線程上得單例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;
}

//類型二、 後臺子線程上得單例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;
}

//統一入口、 提供獲取單例Context對象的入口函數,對不一樣線程提供不一樣的單例Context對象

+ (instancetype)managedObjectContext {
    if ([NSThread isMainThread]) {
        return [self foregroundContext];
    } else {
        return [self backgroundContext];
    }
}
  1. 最後,CoreData自動將實體類模型文件、已經實體類之間的關係,在手機沙盒目錄Document目錄建立數據庫表,並設置表之間的關聯關係。
相關文章
相關標籤/搜索