The Core Data Stack

Core Data Stack有下面的四个类组成:

  1. NSManagedObjectModel
  2. NSPersistentStore
  3. NSPersistentStoreCoordinator
  4. NSManagedObjectContext
实现自己的Core Data Stack
class CoreDataStack {
    
    let modelName = "Dog Walk"
    
    
    
    private lazy var applicationDocumentsDirectory: NSURL = {
        
        
        //返回一个[NSURL]
        
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        print(urls.count)
        
        return urls[urls.count - 1]
        
    }()
    
    
    lazy var context:NSManagedObjectContext = {
        
        
        //一个在主队列中使用的上下文
        var manageObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        //一个持续存储协调器
        manageObjectContext.persistentStoreCoordinator = self.psc
        
        return manageObjectContext
        
    }()
    
    
    private lazy var psc: NSPersistentStoreCoordinator = {
        
        let coordinator: NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.modelName)
        
        do {
            
            let options = [NSMigratePersistentStoresAutomaticallyOption : true]
            
            try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options)
            
        } catch {
            
        }
        
        return coordinator
    }()
    
    private lazy var managedObjectModel: NSManagedObjectModel = {
        
        let modelURL = NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd")!
        
        return NSManagedObjectModel(contentsOfURL: modelURL)!
    }()
    
    
    func saveContext() {
        
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                print("Eror")
                abort()
            }
        }
    }
}```


你可能感兴趣的:(The Core Data Stack)