这一篇,记录下Core Data框架下的 Core Data Stack(其实应该当第一篇的-.-)
Core Data Stack
先上官方给的结构图

Core Data Stack 结构图
Core Data 提供了一些类来合作支持app的模型层处理。
- NSManagedObjectModel: 是我们创建的
.xcdatamodeld文件的编程表示对象 - NSManagedObjectContext: 用于追踪app模型实例的变化
- NSPersistentStoreCoordinator: 持久化存储协调者对象,用来保存或从存储区查询某个模型的实例
如上图,我们通过NSPersistentContainer容器对象来同时创建model、context、store 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;
}