Core Data

appdelegate里生成


    // 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: "coreDataTest")
        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)")
            }
        }
    }

建模不多說 注意實(shí)例化對(duì)象出錯(cuò)的話clean強(qiáng)制退出,重新編譯下

方法

//寫入數(shù)據(jù)
    func insertClass(name: String, score: Double) {
        let context = appDelegate.persistentContainer.viewContext
        
        let people = People(context: context)
        
        people.name = name
        people.score = score
        
        print("正在保存")
        //保存對(duì)象實(shí)體
        
        appDelegate.saveContext()
    }


//讀取所有數(shù)據(jù)(影響性能销斟,不建議用)
    func fetchAllData() {
        
        var peoples : [People] = []
        
        do {
            peoples = try appDelegate.persistentContainer.viewContext.fetch(People.fetchRequest())
        } catch  {
            print(error)
        }
        
    }


//排序讀取所有數(shù)據(jù) (全局變量 var fc: NSFetchedResultsController<People>!)
    func fetchData2() {
        //請(qǐng)求結(jié)果類型是People
        let request: NSFetchRequest<People> = People.fetchRequest()
        //按照name升序
        let sd = NSSortDescriptor(key: "name", ascending: true)
        //NSSortDescriptor指定請(qǐng)求結(jié)果如何排序
        request.sortDescriptors = [sd]
        
        let context = appDelegate.persistentContainer.viewContext
        fc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        fc.delegate = self
        
        do {
            try fc.performFetch()
            if let objects = fc.fetchedObjects {
                peoples = objects
            }
        } catch {
            print(error)
        }
    }

//遵守NSFetchedResultsControllerDelegate代理督暂,與tableview綁定
extension ViewController : NSFetchedResultsControllerDelegate {
    
    //當(dāng)控制器開始處理內(nèi)容變化時(shí)
    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableview.beginUpdates()
    }
    //內(nèi)容發(fā)生變更時(shí)
    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch type {
        case .delete:
            tableview.deleteRows(at: [indexPath!], with: .automatic)
        case .insert:
            tableview.insertRows(at: [newIndexPath!], with: .automatic)
        case .update:
            tableview.reloadRows(at: [indexPath!], with: .automatic)
        default:
            tableview.reloadData()
        }
        if let objects = controller.fetchedObjects {
            peoples = objects as! [People]
        }
    }
    //當(dāng)控制器已經(jīng)處理完變更時(shí)
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableview.endUpdates()
    }
}

//刪除數(shù)據(jù)
  //按條刪除
  let context = appDelegate.persistentContainer.viewContext
context.delete(self.fc.object(at: IndexPath))
appDelegate.saveContext()

  //刪除2
    //刪除數(shù)據(jù)
    func delData() {
        let context = appDelegate.persistentContainer.viewContext
        
        let request: NSFetchRequest<People> = People.fetchRequest()
        
        let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: request) { (result:NSAsynchronousFetchResult) in
            
            //對(duì)返回的數(shù)據(jù)做處理纠修。
            let fetchObject = result.finalResult!
            for c in fetchObject{
                
                //所有刪除信息
                context.delete(c)
            }
            self.appDelegate.saveContext()
            
        }
        
        do {
            try context.execute(asyncFetchRequest)
        } catch  {
            print(error)
        }
    }

import UIKit

import CoreData

class ViewController: UIViewController {

    

    override func viewDidLoad() {

        super.viewDidLoad()

   }

}

 

 

 

//MARK: - CoreData

extension ViewController{

    

//MARK:    獲取上下文對(duì)象

    func getContext() -> NSManagedObjectContext{

        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        return appDelegate.persistentContainer.viewContext

        

    }

    

    

//MARK:    插入班級(jí)信息

    func insertClasses(){

        for i in 1...100{

            let classNO = Int64(i)

            let name = "rg"+"\(i)"

            insertClass(classno:classNO,name:name)

        }

    }

    func insertClass(classno:Int64,name:String) {

        //獲取上下文對(duì)象

        let context = getContext()

        

//        //創(chuàng)建一個(gè)實(shí)例并賦值

//                let classEntity = NSEntityDescription.insertNewObject(forEntityName: "Class", into: context) as! Class

//

//        //Class對(duì)象賦值

//        classEntity.classNo = classno

//        classEntity.name = name

        

        

        //通過指定實(shí)體名 得到對(duì)象實(shí)例

        let Entity = NSEntityDescription.entity(forEntityName: "Class", in: context)

        let classEntity = NSManagedObject(entity: Entity!, insertInto: context)

        classEntity.setValue(classno, forKey: "classNo")

        classEntity.setValue(name, forKey: "name")

        do {

            //保存實(shí)體對(duì)象

            try context.save()

        } catch  {

            let nserror = error as NSError

            fatalError("錯(cuò)誤:\(nserror),\(nserror.userInfo)")

        }

    }

    

 

//MARK:    查詢班級(jí)信息

    func getClass(){

        

//        異步fetch

        

        //獲取數(shù)據(jù)上下文對(duì)象

        let context = getContext()

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")

 

        // 異步請(qǐng)求由兩部分組成:普通的request和completion handler

        // 返回結(jié)果在finalResult中

        let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result : NSAsynchronousFetchResult!) in

            

            //對(duì)返回的數(shù)據(jù)做處理。

            let fetchObject = result.finalResult as! [Class]

 

            for  c in fetchObject{

                print("\(c.classNo),\(c.name ?? "")")

            }

        }

        

        // 執(zhí)行異步請(qǐng)求調(diào)用execute

        do {

            try context.execute(asyncFetchRequest)

   

        } catch  {

            print("error")

        }

 

    }

    

//MARK:    修改班級(jí)信息

    func modifyClass() {

        //獲取委托

        let app = UIApplication.shared.delegate as! AppDelegate

        //獲取數(shù)據(jù)上下文對(duì)象

        let context = getContext()

        //聲明數(shù)據(jù)的請(qǐng)求,聲明一個(gè)實(shí)體結(jié)構(gòu)

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")

        //查詢條件

        fetchRequest.predicate = NSPredicate(format: "classNo = 2", "")

        

        // 異步請(qǐng)求由兩部分組成:普通的request和completion handler

        // 返回結(jié)果在finalResult中

        let asyncFecthRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result: NSAsynchronousFetchResult!) in

            

            //對(duì)返回的數(shù)據(jù)做處理啸如。

            let fetchObject  = result.finalResult! as! [Class]

            for c in fetchObject{

                c.name = "qazwertdfxcvg"

                app.saveContext()

            }

        }

        

        // 執(zhí)行異步請(qǐng)求調(diào)用execute

        do {

            try context.execute(asyncFecthRequest)

        } catch  {

            print("error")

        }

 

    }

    

//MARK:    刪除班級(jí)信息

 

    func deleteClass() -> Void {

        //獲取委托

        let app = UIApplication.shared.delegate as! AppDelegate

        

        //獲取數(shù)據(jù)上下文對(duì)象

        let context = getContext()

       

        //聲明數(shù)據(jù)的請(qǐng)求腥寇,聲明一個(gè)實(shí)體結(jié)構(gòu)

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")

        

        // 異步請(qǐng)求由兩部分組成:普通的request和completion handler

        // 返回結(jié)果在finalResult中

        let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result:NSAsynchronousFetchResult) in

           

            //對(duì)返回的數(shù)據(jù)做處理成翩。

            let fetchObject = result.finalResult! as! [Class]

            for c in fetchObject{

                

                //所有刪除信息

                context.delete(c)

            }

             app.saveContext()

        }

        

          // 執(zhí)行異步請(qǐng)求調(diào)用execute

        do {

            try context.execute(asyncFetchRequest)

        } catch  {

            print("error")

        }

    }

    

    //MARK:    統(tǒng)計(jì)信息

    func countClass() {

        //獲取數(shù)據(jù)上下文對(duì)象

        let context = getContext()

        

        

        //聲明數(shù)據(jù)的請(qǐng)求,聲明一個(gè)實(shí)體結(jié)構(gòu)

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")

        

        //請(qǐng)求的描述赦役,按classNo 從小到大排序

        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "classNo", ascending: true)]

        

        //請(qǐng)求的結(jié)果類型

        //        NSManagedObjectResultType:返回一個(gè)managed object(默認(rèn)值)

        //        NSCountResultType:返回滿足fetch request的object數(shù)量

        //        NSDictionaryResultType:返回字典結(jié)果類型

        //        NSManagedObjectIDResultType:返回唯一的標(biāo)示符而不是managed object

        fetchRequest.resultType = .dictionaryResultType

        

        // 創(chuàng)建NSExpressionDescription來請(qǐng)求進(jìn)行平均值計(jì)算麻敌,取名為AverageNo,通過這個(gè)名字掂摔,從fetch請(qǐng)求返回的字典中找到平均值

        let description = NSExpressionDescription()

        description.name = "AverageNo"

        

        

        //指定要進(jìn)行平均值計(jì)算的字段名classNo并設(shè)置返回值類型

        let args  = [NSExpression(forKeyPath: "classNo")]

        

        // forFunction參數(shù)有sum:求和 count:計(jì)算個(gè)數(shù) min:最小值 max:最大值 average:平均值等等

        description.expression = NSExpression(forFunction: "average:", arguments: args)

        description.expressionResultType = .floatAttributeType

 

        // 設(shè)置請(qǐng)求的propertiesToFetch屬性為description告訴fetchRequest术羔,我們需要對(duì)數(shù)據(jù)進(jìn)行求平均值

        fetchRequest.propertiesToFetch = [description]

        

        do {

            let entries =  try context.fetch(fetchRequest)

            let result = entries.first! as! NSDictionary

            let averageNo = result["AverageNo"]!

            print("\(averageNo)")

            

        } catch  {

            print("failed")

        }

    }

    

    

    //MARK:批量更新

    func batchUpdate()

    {

        let batchUpdate = NSBatchUpdateRequest(entityName: "Class")

        //所要更新的屬性 和 更新的值

        batchUpdate.propertiesToUpdate = ["name": 55555]

        //被影響的Stores

        batchUpdate.affectedStores = self.getContext().persistentStoreCoordinator!.persistentStores

        //配置返回?cái)?shù)據(jù)的類型

        batchUpdate.resultType = .updatedObjectsCountResultType

 

        //執(zhí)行批量更新

        do {

           let batchResult = try getContext().execute(batchUpdate) as! NSBatchUpdateResult

        //批量更新的結(jié)果,上面resultType類型指定為updatedObjectsCountResultType乙漓,所以result顯示的為 更新的個(gè)數(shù)

           print("\(batchResult.result!)")

        } catch   {

            print("error")

        }

    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末级历,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子簇秒,更是在濱河造成了極大的恐慌鱼喉,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,183評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異扛禽,居然都是意外死亡锋边,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門编曼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來豆巨,“玉大人,你說我怎么就攤上這事掐场⊥樱” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵熊户,是天一觀的道長萍膛。 經(jīng)常有香客問我,道長嚷堡,這世上最難降的妖魔是什么蝗罗? 我笑而不...
    開封第一講書人閱讀 59,854評(píng)論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮蝌戒,結(jié)果婚禮上串塑,老公的妹妹穿的比我還像新娘。我一直安慰自己北苟,他們只是感情好桩匪,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,871評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著友鼻,像睡著了一般傻昙。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上桃移,一...
    開封第一講書人閱讀 52,457評(píng)論 1 311
  • 那天屋匕,我揣著相機(jī)與錄音,去河邊找鬼借杰。 笑死,一個(gè)胖子當(dāng)著我的面吹牛进泼,可吹牛的內(nèi)容都是我干的蔗衡。 我是一名探鬼主播,決...
    沈念sama閱讀 40,999評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼乳绕,長吁一口氣:“原來是場噩夢啊……” “哼绞惦!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起洋措,我...
    開封第一講書人閱讀 39,914評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤济蝉,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體王滤,經(jīng)...
    沈念sama閱讀 46,465評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡贺嫂,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,543評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了雁乡。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片第喳。...
    茶點(diǎn)故事閱讀 40,675評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖踱稍,靈堂內(nèi)的尸體忽然破棺而出曲饱,到底是詐尸還是另有隱情,我是刑警寧澤珠月,帶...
    沈念sama閱讀 36,354評(píng)論 5 351
  • 正文 年R本政府宣布扩淀,位于F島的核電站,受9級(jí)特大地震影響啤挎,放射性物質(zhì)發(fā)生泄漏引矩。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,029評(píng)論 3 335
  • 文/蒙蒙 一侵浸、第九天 我趴在偏房一處隱蔽的房頂上張望旺韭。 院中可真熱鬧,春花似錦掏觉、人聲如沸区端。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽织盼。三九已至,卻和暖如春酱塔,著一層夾襖步出監(jiān)牢的瞬間沥邻,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評(píng)論 1 274
  • 我被黑心中介騙來泰國打工羊娃, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留唐全,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,091評(píng)論 3 378
  • 正文 我出身青樓蕊玷,卻偏偏與公主長得像邮利,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子垃帅,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,685評(píng)論 2 360

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

  • 引言 在這個(gè)教程中延届,你會(huì)看到在Xcode提供的初始化代碼模板和數(shù)據(jù)模型編輯器資源中,用Swift語言寫出你的第一個(gè)...
    MarkLin閱讀 10,172評(píng)論 7 32
  • 適讀對(duì)象: 需要入門Core Data的朋友贸诚; 像我一樣方庭,尚未學(xué)過數(shù)據(jù)庫相關(guān)課程厕吉,不太懂怎么寫SQLite語句的朋...
    AntonyWong閱讀 5,250評(píng)論 8 21
  • 1 前言 CoreData不僅僅是數(shù)據(jù)庫,而是蘋果封裝的一個(gè)更高級(jí)的數(shù)據(jù)持久化框架械念,SQLite只是其提供的一種數(shù)...
    RichardJieChen閱讀 3,012評(píng)論 2 2
  • 版本記錄 前言 數(shù)據(jù)是移動(dòng)端的重點(diǎn)關(guān)注對(duì)象头朱,其中有一條就是數(shù)據(jù)存儲(chǔ)。CoreData是蘋果出的數(shù)據(jù)存儲(chǔ)和持久化技術(shù)...
    刀客傳奇閱讀 2,848評(píng)論 0 6
  • 推薦指數(shù): 6.0 書籍主旨關(guān)鍵詞:特權(quán)订讼、焦點(diǎn)髓窜、注意力、語言聯(lián)想欺殿、情景聯(lián)想 觀點(diǎn): 1.統(tǒng)計(jì)學(xué)現(xiàn)在叫數(shù)據(jù)分析寄纵,社會(huì)...
    Jenaral閱讀 5,726評(píng)論 0 5