這一篇痰娱,記錄下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
文件的編程表示對象 - NSManagedObjectContext: 用于追蹤app模型實(shí)例的變化
- NSPersistentStoreCoordinator: 持久化存儲(chǔ)協(xié)調(diào)者對象,用來保存或從存儲(chǔ)區(qū)查詢某個(gè)模型的實(shí)例
如上圖谐鼎,我們通過NSPersistentContainer
容器對象來同時(shí)創(chuàng)建model
、context
鞋喇、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;
}