关于Core Data的一些整理(三)
关于Core Data Stack的四种类与它们的关系如下:
- NSManagedObjectModel
- NSPersistentStore
- NSPersistentStoreCoordinator
- NSManagedObjectContext
手写Core Data Stack,新建文件继承NSObject,并且在其中要依次初始化三个对象:NSManagedObjectContext
、NSPersistentStoreCoordinator
、NSManagedObjectModel
,具体代码实现如下:
1 // CoreDataStack.h 2 3 #import4 #import 5 6 @interface CoreDataStack : NSObject 7 8 @property (nonatomic, strong) NSManagedObjectContext *context; 9 10 - (void)saveContext;11 12 @end13 14 // CoreDataStack.m15 16 #import "CoreDataStack.h"17 18 @interface CoreDataStack ()19 20 @property (nonatomic, strong) NSPersistentStoreCoordinator *psc;21 @property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;22 23 @end24 25 @implementation CoreDataStack26 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
需要注意的地方为:
- 所有全局变量均为惰性加载,提高效率;
- 只用将
NSManagedObjectContext
放到.h中去即可; - 调用addPersistentStoreWithType:方法时注意将数据库文件命名为sqlite后缀的类型,否则会报错;
- 注意命名的一致性,在代码中均使用
JMDog_Walk
,在建立Core Data文件时,也要将文件命名为JMDog_Walk
!