iOS 数据库相关随笔(3) —— Core Data Stack

这一篇,记录下Core Data框架下的 Core Data Stack(其实应该当第一篇的-.-)

Core Data Stack

先上官方给的结构图


Core Data Stack 结构图

Core Data 提供了一些类来合作支持app的模型层处理。

  • NSManagedObjectModel: 是我们创建的.xcdatamodeld文件的编程表示对象
  • NSManagedObjectContext: 用于追踪app模型实例的变化
  • NSPersistentStoreCoordinator: 持久化存储协调者对象,用来保存或从存储区查询某个模型的实例

如上图,我们通过NSPersistentContainer容器对象来同时创建modelcontextstore coordinator

NSPersistentContainer ——用来封装app Core Data stack的容器

当我们在创建工程勾选使用core data后,在AppDelegate.m文件中,会自动生成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;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容