關於Core Data的一些整理(三)

關於Core Data的一些整理(三)

關於Core Data Stack的四種類與它們的關係以下:sql

  •  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

須要注意的地方爲:app

  1. 全部全局變量均爲惰性加載,提升效率;
  2. 只用將NSManagedObjectContext​放到.h中去便可;
  3. 調用addPersistentStoreWithType:方法時注意將數據庫文件命名爲sqlite後綴的類型,不然會報錯;
  4. 注意命名的一致性,在代碼中均使用JMDog_Walk,在創建Core Data文件時,也要將文件命名爲JMDog_Walk
相關文章
相關標籤/搜索