关于Core Data的一些整理(三)

关于Core Data的一些整理(三)

关于Core Data Stack的四种类与它们的关系如下:

  •  NSManagedObjectModel
  •  NSPersistentStore
  •  NSPersistentStoreCoordinator 
  •  NSManagedObjectContext

 

 

手写Core Data Stack,新建文件继承NSObject,并且在其中要依次初始化三个对象:NSManagedObjectContextNSPersistentStoreCoordinatorNSManagedObjectModel,具体代码实现如下:

 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

需要注意的地方为:

  1. 所有全局变量均为惰性加载,提高效率;
  2. 只用将NSManagedObjectContext​放到.h中去即可;
  3. 调用addPersistentStoreWithType:方法时注意将数据库文件命名为sqlite后缀的类型,否则会报错;
  4. 注意命名的一致性,在代码中均使用JMDog_Walk,在建立Core Data文件时,也要将文件命名为JMDog_Walk

 

 

posted @ 2016-01-14 18:38  jackma86  阅读(174)  评论(0编辑  收藏  举报