关于Core Data的一些整理(三)
关于Core Data Stack的四种类与它们的关系如下:
- NSManagedObjectModel
- NSPersistentStore
- NSPersistentStoreCoordinator
- NSManagedObjectContext
手写Core Data Stack,新建文件继承NSObject,并且在其中要依次初始化三个对象:NSManagedObjectContext
、NSPersistentStoreCoordinator
、NSManagedObjectModel
,具体代码实现如下:
// CoreDataStack.h #import <Foundation/Foundation.h>
#import <CoreData/CoreData.h> @interface CoreDataStack : NSObject @property (nonatomic, strong) NSManagedObjectContext *context; - (void)saveContext; @end // CoreDataStack.m #import "CoreDataStack.h" @interface CoreDataStack () @property (nonatomic, strong) NSPersistentStoreCoordinator *psc;
@property (nonatomic, strong) NSManagedObjectModel *managedObjectModel; @end @implementation CoreDataStack @synthesize managedObjectModel = _managedObjectModel; - (void)saveContext {
if (_context) {
NSError *error = nil;
if ([_context hasChanges] && [_context save:&error]) {
NSLog(@"%@", error.localizedDescription);
abort();
}
}
} - (NSURL *)applicationDocumentsDirectory {
NSArray *array = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
return array.lastObject;
} - (NSManagedObjectContext *)context {
if (_context) {
return _context;
}
_context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_context setPersistentStoreCoordinator:[self psc]];
return _context;
} - (NSPersistentStoreCoordinator *)psc {
if (_psc) {
return _psc;
}
_psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *url = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"JMDog_Walk.sqlite"];
[_psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:@{NSMigratePersistentStoresAutomaticallyOption:@} error:nil];
return _psc;
} - (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel) {
return _managedObjectModel;
}
NSURL *url = [[NSBundle mainBundle] URLForResource:@"JMDog_Walk" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
return _managedObjectModel;
} @end
需要注意的地方为:
- 所有全局变量均为惰性加载,提高效率;
- 只用将
NSManagedObjectContext
放到.h中去即可; - 调用addPersistentStoreWithType:方法时注意将数据库文件命名为sqlite后缀的类型,否则会报错;
- 注意命名的一致性,在代码中均使用
JMDog_Walk
,在建立Core Data文件时,也要将文件命名为JMDog_Walk
!