初始化Core Data的三个方法:
- init,初始化托管对象模型、持久化存储协调器、托管对象上下文
-
- (id)init { if (debug == 1) { 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; }
NSMainQueueConcurrencyType表示在主线程队列运行。
-
- loadStore:创建并加载持久化存储区
-
- (void)loadStore { if (debug == 1) { 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 == 1){ NSLog(@"Successfully add store: %@", _store); } }
-
- 加载持久化存储区
-
- (void)setupCoreData { if (debug == 1) { NSLog(@"Running %@ '%@'",self.class, NSStringFromSelector(_cmd)); } [self loadStore]; }
-