iOS 數(shù)據(jù)庫相關(guān)隨筆(3) —— Core Data Stack

這一篇,記錄下Core Data框架下的 Core Data Stack(其實(shí)應(yīng)該當(dāng)?shù)谝黄?.-)

Core Data Stack

先上官方給的結(jié)構(gòu)圖


Core Data Stack 結(jié)構(gòu)圖

Core Data 提供了一些類來合作支持app的模型層處理。

  • NSManagedObjectModel: 是我們創(chuàng)建的.xcdatamodeld文件的編程表示對(duì)象
  • NSManagedObjectContext: 用于追蹤app模型實(shí)例的變化
  • NSPersistentStoreCoordinator: 持久化存儲(chǔ)協(xié)調(diào)者對(duì)象,用來保存或從存儲(chǔ)區(qū)查詢某個(gè)模型的實(shí)例

如上圖,我們通過NSPersistentContainer容器對(duì)象來同時(shí)創(chuàng)建modelcontext、store coordinator

NSPersistentContainer ——用來封裝app Core Data stack的容器

當(dāng)我們在創(chuàng)建工程勾選使用core data后,在AppDelegate.m文件中,會(huì)自動(dòng)生成core data stack的set up模塊

#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"YWHCoreDataDemo"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // 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 parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容