CoreData的使用(一)

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

一沛婴、基本使用

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


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


      項(xiàng)目中創(chuàng)建.png
  • Appdelegate中的一些配置
    • 如果你是創(chuàng)建項(xiàng)目的時(shí)候就選擇了CoreData的話,你會(huì)發(fā)現(xiàn)在Appdelegate中會(huì)有這么一段代碼躲舌,但是這個(gè)是在iOS10的環(huán)境下的丑婿,如果你的項(xiàng)目需要支持9,8没卸,7的話羹奉,就不能這么使用了,Xcode會(huì)報(bào)錯(cuò)的约计。诀拭。。
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)")
            }
        }
    }
  • 如果你是后來在項(xiàng)目中新建的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()
            }
        }
    }
  • 為了方便使用我們定一個(gè)全局的CONTEXT
let CONTEXT = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext

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


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


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


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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市良哲,隨后出現(xiàn)的幾起案子盛卡,更是在濱河造成了極大的恐慌,老刑警劉巖筑凫,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件滑沧,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡巍实,警方通過查閱死者的電腦和手機(jī)滓技,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來棚潦,“玉大人令漂,你說我怎么就攤上這事⊥璞撸” “怎么了叠必?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長妹窖。 經(jīng)常有香客問我纬朝,道長,這世上最難降的妖魔是什么骄呼? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任玄组,我火速辦了婚禮,結(jié)果婚禮上谒麦,老公的妹妹穿的比我還像新娘俄讹。我一直安慰自己,他們只是感情好绕德,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布患膛。 她就那樣靜靜地躺著,像睡著了一般耻蛇。 火紅的嫁衣襯著肌膚如雪踪蹬。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天臣咖,我揣著相機(jī)與錄音跃捣,去河邊找鬼。 笑死夺蛇,一個(gè)胖子當(dāng)著我的面吹牛疚漆,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼娶聘,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼闻镶!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起丸升,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤铆农,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后狡耻,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體墩剖,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年夷狰,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了岭皂。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡孵淘,死狀恐怖蒲障,靈堂內(nèi)的尸體忽然破棺而出歹篓,到底是詐尸還是另有隱情瘫证,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布庄撮,位于F島的核電站背捌,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏洞斯。R本人自食惡果不足惜毡庆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望烙如。 院中可真熱鬧么抗,春花似錦、人聲如沸亚铁。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽徘溢。三九已至吞琐,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間然爆,已是汗流浹背站粟。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留曾雕,地道東北人奴烙。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親缸沃。 傳聞我的和親對(duì)象是個(gè)殘疾皇子恰起,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

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

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,478評(píng)論 5 6
  • 如果沒有約束,這會(huì)是怎樣的一個(gè)世界呢趾牧? 人常在不同場(chǎng)合检盼,扮演不同的角色。 現(xiàn)實(shí)生活中翘单,當(dāng)我們?cè)谕露滞鳌⒂讶嘶蛘吣吧?..
    娃子哥閱讀 1,320評(píng)論 0 4
  • 參不參加由你定,有啥意見跟我說哄芜。 若是心打退堂鼓貌亭,惡魔都在鄙視你。 身體不適也可以认臊,下次你來我歡迎圃庭! 要是想來給我...
    劉婧_閱讀 251評(píng)論 5 17
  • 今天整理衣柜的時(shí)候,看到我珍藏的兩只玩偶靜靜的躺在柜子的角路里失晴,不禁感嘆萬分剧腻。 那兩只玩偶其實(shí)很袖珍,只有巴掌那么...
    在水一方含閱讀 337評(píng)論 2 2
  • 在我記憶里爸媽都沒怎么變過涂屁,可是今天我才猛然發(fā)現(xiàn)书在,爸媽都有白發(fā)了,可是我還沒能力給他們好的生活呢拆又,等等我可好儒旬?
    Violetcold閱讀 163評(píng)論 0 0