初始化Core Data的三个方法:
- init,初始化托管对象模型、持久化存储协调器、托管对象上下文
-
- (id)init {
if (debug == ) {
NSLog(@"Running %@ '%@'",self.class, NSStringFromSelector(_cmd));
} if (self = [super init]) {
_model = [NSManagedObjectModel mergedModelFromBundles:nil];
_coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_model];
_context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_context setPersistentStoreCoordinator:_coordinator];
} return self;
}_model 的mergedModelBundles的参数为nil,表示要用main bundle里面所有的数据模型文件都初始化进来。如果有多个模型文件需要合并,可以把元素类型为NSBundles的NSArray数组传给mergedModelBundles。
NSMainQueueConcurrencyType表示在主线程队列运行。
-
- loadStore:创建并加载持久化存储区
- (void)loadStore {
if (debug == ) {
NSLog(@"Running %@ '%@'",self.class, NSStringFromSelector(_cmd));
} if (_store) {return;} NSError *error = nil;
_store = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self storeURL] options:nil error:&error]; if (!_store) {
NSLog(@"Failded to add store. Error: %@", error);
abort();
}else if (debug == ){
NSLog(@"Successfully add store: %@", _store);
}
}
- 加载持久化存储区
- (void)setupCoreData {
if (debug == ) {
NSLog(@"Running %@ '%@'",self.class, NSStringFromSelector(_cmd));
} [self loadStore];
}