CoreDataStack

//
//  Stack.swift
//  Bubble Tea Finder
//
//  Copyright © 2016 Pietro Rea. All rights reserved.
//

import CoreData
class CoreDataStack {
    let modelName = "Bubble_Tea_Finder"
    
    private lazy var applicationDirectoryPath: NSURL = {
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        let url = urls[urls.count - 1]
        print("沙盒路径:\(url)")
        return url
    }()
    
    lazy var context: NSManagedObjectContext = {
        let managedContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        managedContext.persistentStoreCoordinator = self.persistentStoreCoordinator
        return managedContext
    }()
    
    private lazy var persistentStoreCoordinator:NSPersistentStoreCoordinator = {
        let psc = NSPersistentStoreCoordinator(managedObjectModel: self.model)
        let url = self.applicationDirectoryPath.URLByAppendingPathComponent(self.modelName)
        let options = [NSMigratePersistentStoresAutomaticallyOption : true]
        do{
            try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options)
        } catch let error as NSError{
            print("Error add persistent store : \(error)")
        }
        return psc
    }()
    
    private lazy var model: NSManagedObjectModel = {
        let url = NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd")
        print("资源路径:\(url)")
        let model = NSManagedObjectModel(contentsOfURL: url!)
        return model!
    }()
    
    func saveContext() {
        if context.hasChanges {
            do {
                try context.save()
            } catch let error as NSError{
                print("Error save : \(error)")
                abort()
            }
        }
    }
}

保存失败后,要断开连接

1、获取资源用NSBundle

2、获取沙盒路径用NSFileManager

posted @ 2016-03-29 11:27  GrandKai  阅读(240)  评论(0编辑  收藏  举报