關於Core Data Stack的四種類與它們的關係以下:sql
手寫Core Data Stack,新建文件繼承NSObject,而且在其中要依次初始化三個對象:NSManagedObjectContext
、NSPersistentStoreCoordinator
、NSManagedObjectModel
,具體代碼實現以下:數據庫
1 // CoreDataStack.h 2 3 #import <Foundation/Foundation.h> 4 #import <CoreData/CoreData.h> 5 6 @interface CoreDataStack : NSObject 7 8 @property (nonatomic, strong) NSManagedObjectContext *context; 9 10 - (void)saveContext; 11 12 @end 13 14 // CoreDataStack.m 15 16 #import "CoreDataStack.h" 17 18 @interface CoreDataStack () 19 20 @property (nonatomic, strong) NSPersistentStoreCoordinator *psc; 21 @property (nonatomic, strong) NSManagedObjectModel *managedObjectModel; 22 23 @end 24 25 @implementation CoreDataStack 26 27 @synthesize managedObjectModel = _managedObjectModel; 28 29 - (void)saveContext { 30 if (_context) { 31 NSError *error = nil; 32 if ([_context hasChanges] && [_context save:&error]) { 33 NSLog(@"%@", error.localizedDescription); 34 abort(); 35 } 36 } 37 } 38 39 - (NSURL *)applicationDocumentsDirectory { 40 NSArray *array = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]; 41 return array.lastObject; 42 } 43 44 - (NSManagedObjectContext *)context { 45 if (_context) { 46 return _context; 47 } 48 _context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; 49 [_context setPersistentStoreCoordinator:[self psc]]; 50 return _context; 51 } 52 53 - (NSPersistentStoreCoordinator *)psc { 54 if (_psc) { 55 return _psc; 56 } 57 _psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 58 NSURL *url = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"JMDog_Walk.sqlite"]; 59 [_psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:@{NSMigratePersistentStoresAutomaticallyOption:@1} error:nil]; 60 return _psc; 61 } 62 63 - (NSManagedObjectModel *)managedObjectModel { 64 if (_managedObjectModel) { 65 return _managedObjectModel; 66 } 67 NSURL *url = [[NSBundle mainBundle] URLForResource:@"JMDog_Walk" withExtension:@"momd"]; 68 _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:url]; 69 return _managedObjectModel; 70 } 71 72 @end
須要注意的地方爲:app
NSManagedObjectContext
放到.h中去便可;JMDog_Walk
,在創建Core Data文件時,也要將文件命名爲JMDog_Walk
!