CoreData的使用(一)

CoreData是蘋果自帶的一種持久化數(shù)據(jù)存儲的方式,網(wǎng)上很多人說使用起來麻煩,其實正真使用后發(fā)現(xiàn)還是蠻方便的,又是系統(tǒng)自帶的,其實我還是蠻推薦使用的

一、基本使用

  • 創(chuàng)建
    • 創(chuàng)建項目的時候勾選CoreData


      項目創(chuàng)建.png
    • 創(chuàng)建項目的時候如果未選擇CoreData的話也沒有關(guān)系,可以在項目中選擇new->file(comand+n)。找到CoreData->Data Model,創(chuàng)建


      項目中創(chuàng)建.png
  • Appdelegate中的一些配置
    • 如果你是創(chuàng)建項目的時候就選擇了CoreData的話,你會發(fā)現(xiàn)在Appdelegate中會有這么一段代碼,但是這個是在iOS10的環(huán)境下的,如果你的項目需要支持9,8,7的話,就不能這么使用了,Xcode會報錯的。。。
func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "CoreDataDemo")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
  • 如果你是后來在項目中新建的Data Model的話,上面這一段代碼需要自行添加,下面的一段,在iOS7,8,9,10下都可以的,建議大家替換掉
func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack
    
    lazy var applicationDocumentsDirectory: NSURL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "com.hongyu.wsl.BellEdu" in the application's documents Application Support directory.
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return urls[urls.count-1] as NSURL
    }()
    
    lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
       //Resource的名字最好是和Data Model的名字相同
        let modelURL = Bundle.main.url(forResource: "CoreDataDemo", withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()
    
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
        // Create the coordinator and store
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        
        /// 數(shù)據(jù)遷移,option使用于一般的數(shù)據(jù)遷移
        let option = [NSMigratePersistentStoresAutomaticallyOption:NSNumber(value: true),NSInferMappingModelAutomaticallyOption:NSNumber(value: true)]
        do {
            try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: option)
        } catch {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
            dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
            
            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }
        
        return coordinator
    }()
    
    lazy var managedObjectContext: NSManagedObjectContext = {
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()
    
    // MARK: - Core Data Saving support
    
    func saveContext () {
        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }
  • 為了方便使用我們定一個全局的CONTEXT
let CONTEXT = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext

  • 數(shù)據(jù)模型的創(chuàng)建
  • 找到Data Model,點擊Add Entity,


    Add Entity.png
  • 輸入model的類名,它的屬性定義,屬性的類型等


    Entity.png
  • Editor->Creat NSManagedObject Subclass 創(chuàng)建數(shù)據(jù)模型


    數(shù)據(jù)模型創(chuàng)建.png
  • 創(chuàng)建成功后,會生成DemoModel+CoreDataClass.swift和DemoModel+CoreDataProperties.swift這2個文件

下一節(jié):CoreData的使用(二)---增刪改查

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,551評論 5 6
  • 如果沒有約束,這會是怎樣的一個世界呢? 人常在不同場合,扮演不同的角色。 現(xiàn)實生活中,當(dāng)我們在同事、友人或者陌生人...
    娃子哥閱讀 1,329評論 0 4
  • 參不參加由你定,有啥意見跟我說。 若是心打退堂鼓,惡魔都在鄙視你。 身體不適也可以,下次你來我歡迎! 要是想來給我...
    劉婧_閱讀 257評論 5 17
  • 今天整理衣柜的時候,看到我珍藏的兩只玩偶靜靜的躺在柜子的角路里,不禁感嘆萬分。 那兩只玩偶其實很袖珍,只有巴掌那么...
    在水一方含閱讀 352評論 2 2
  • 在我記憶里爸媽都沒怎么變過,可是今天我才猛然發(fā)現(xiàn),爸媽都有白發(fā)了,可是我還沒能力給他們好的生活呢,等等我可好?
    Violetcold閱讀 167評論 0 0