美文网首页
CoreData 的基本原理

CoreData 的基本原理

作者: 小黑Swift | 来源:发表于2016-03-17 00:23 被阅读259次
    CoreData

    CoreDataStack.swift

    import UIKit
    import CoreData
    
    class CoreDataStack: NSObject {
        
        // MARK: - Properties(属性)
        let context: NSManagedObjectContext
        let coordinator: NSPersistentStoreCoordinator
        let model: NSManagedObjectModel
        let store: NSPersistentStore?
        
        // MARK: - Singleton(单例)
        static func defaultStack() -> CoreDataStack {
            return instance 
        }
        
        private static let instance = CoreDataStack()
        
        private override init() {
            // 构建托管对象模型
            let bundle = NSBundle.mainBundle()
            let modelURL = bundle.URLForResource("FileName", withExtension: "momd")!
            model = NSManagedObjectModel(contentsOfURL: modelURL)!
            
            // 构建持久化存储助理
            coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
            
            // 构建托管对象上下文,并且将助理与上下文连接
            context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
            context.persistentStoreCoordinator = coordinator
            
            // 构建持久化存储
            let manager = NSFileManager.defaultManager()
            let urls = manager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
            let documentsURL = urls.first!
            let storeURL = documentsURL.URLByAppendingPathComponent("FileName")
            
            store = try! coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
         }
        
        // MARK: - Function
        func saveContext() {
            if context.hasChanges {
                do {
                    try context.save()
                } catch {
                    print("Save failed...")
                }
            }
        }
    }
    

    手动设置时候,别忘记了在程序终止时候调用保存数据等

    func applicationWillTerminate(application: UIApplication) {
        CoreDataStack.defaultStack().saveContext()
    }

    相关文章

      网友评论

          本文标题:CoreData 的基本原理

          本文链接:https://www.haomeiwen.com/subject/rkfclttx.html