swift簡單實用coreData

在開發(fā)中經(jīng)常會涉及到本地數(shù)據(jù)的存儲。一般使用比較多的有,plist,本地文件,SQLite,coredata。根據(jù)要存儲的數(shù)據(jù)類型選擇對應的方法存儲數(shù)據(jù)。在數(shù)據(jù)比較復雜時我選用coredata。最初使用原生的SQLite,修改比較麻煩,最后換成了coredata。操作步驟如下:
創(chuàng)建DataModel文件。


image.png

在DataModel中創(chuàng)建數(shù)據(jù)表,然后在數(shù)據(jù)表中創(chuàng)建對應的數(shù)據(jù)字段。

創(chuàng)建一個存儲調度器,名字就是上面創(chuàng)建的dataModel文件名

  lazy var persistentContainer: NSPersistentContainer = {
        
        let container = NSPersistentContainer(name: "LocalDataModel")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

  func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

為了方便操作,我們創(chuàng)建一個類用來添加,刪除,修改,查詢數(shù)據(jù)。

import Foundation
import CoreData

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObectContext = appDelegate.persistentContainer.viewContext

class CoreDataManager: NSObject {
    
    //添加數(shù)據(jù)(添加的數(shù)據(jù)比較多時,可以使用模型)
    func instertDeviceData(dLatitude:Double,
                           dLongitude:Double,
                           tInspectorName:String,
                           tInspectDateTime:String,
                           tCheckTaskGuid:String,
                           tCheckTaskName:String,
                           tSystemStatus:String,
                           iDeviceCheckStatus:Int16,
                           tDeviceGuid:String,
                           tDeviceName:String,
                           tDeviceCode:String,
                           tDeviceLocation:String,
                           tDeviceDescription:String,
                           tNodeGuid:String,
                           tNodeName:String,
                           tNodeCode:String,
                           iEmptyNodeStatus:Int16,
                           tNodeLocation:String,
                           tNodeDescription:String,
                           isChecked:Int) -> Bool{
        
        let dataModel = NSEntityDescription.insertNewObject(forEntityName: "Inspect_Device_Table", into: managedObectContext) as! Inspect_Device_Table
        
        dataModel.dLatitude                 = dLatitude
        dataModel.dLongitude                = dLongitude
        dataModel.tInspectorName            = tInspectorName
        dataModel.tInspectDateTime          = tInspectDateTime
        dataModel.iIsChecked                = Int16(isChecked)
        
        dataModel.tCheckTaskGuid            = tCheckTaskGuid
        dataModel.tCheckTaskName            = tCheckTaskName
        
        dataModel.tSystemStatus             = tSystemStatus
        dataModel.iDeviceCheckStatus        = iDeviceCheckStatus
        dataModel.tDeviceGuid               = tDeviceGuid
        dataModel.tDeviceName               = tDeviceName
        dataModel.tDeviceCode               = tDeviceCode
        dataModel.tDeviceLocation           = tDeviceLocation
        dataModel.tDeviceDescription        = tDeviceDescription

        dataModel.tNodeGuid                 = tNodeGuid
        dataModel.tNodeName                 = tNodeName
        dataModel.tNodeCode                 = tNodeCode
        dataModel.iEmptyNodeStatus          = iEmptyNodeStatus
        dataModel.tNodeLocation             = tNodeLocation
        dataModel.tNodeDescription          = tNodeDescription
        do {
            try managedObectContext.save()
            print("數(shù)據(jù)保存成功")
            return true
        }catch{
            print("數(shù)據(jù)保存失敗")
            return false

        }
        
    }
    //查詢數(shù)據(jù)
    func selecteDeviceData(tCheckTaskGuid:String,tDeviceGuid:String,tNodeGuid:String) ->Array<Inspect_Device_Table> {
        var deviceArray = Array<Inspect_Device_Table>()
        //  建立一個獲取的請求
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Inspect_Device_Table")
        
        //設置查詢條件
        if tNodeGuid == "" {
            if tDeviceGuid == "" {
                fetchRequest.predicate = NSPredicate(format: "tCheckTaskGuid=%@ ", tCheckTaskGuid)
            }else{
                fetchRequest.predicate = NSPredicate(format: "tCheckTaskGuid=%@ and tDeviceGuid=%@", tCheckTaskGuid,tDeviceGuid)
            }
        }else{
            if tDeviceGuid == "" {
                fetchRequest.predicate = NSPredicate(format: "tCheckTaskGuid=%@ and tNodeGuid=%@", tCheckTaskGuid,tNodeGuid)
            }else{
                fetchRequest.predicate = NSPredicate(format: "tCheckTaskGuid=%@ and tNodeGuid=%@ and tDeviceGuid=%@", tCheckTaskGuid,tNodeGuid,tDeviceGuid)
            }
        }
        // 執(zhí)行請求  
        do {
            let fetchedResults = try managedObectContext.fetch(fetchRequest) as? [NSManagedObject]
            
            if let results = fetchedResults {

                deviceArray.removeAll()
                for model in results {
                    deviceArray.append(model as! Inspect_Device_Table)
                }
            }
            print("數(shù)據(jù)讀取成功")
            return deviceArray
        } catch  {
            print("數(shù)據(jù)讀取失敗")
            return deviceArray
        }
    }
    //刪除指定數(shù)據(jù)
    func deleteDeviceData(tCheckTaskGuid:String,tNodeGuid:String,tDeviceGuid:String) ->Bool {
        //  建立一個獲取的請求
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Inspect_Device_Table")
        
        if tNodeGuid == "" {
            if tDeviceGuid == "" {
                fetchRequest.predicate = NSPredicate(format: "tCheckTaskGuid=%@ ", tCheckTaskGuid)
            }else{
                fetchRequest.predicate = NSPredicate(format: "tCheckTaskGuid=%@ and tDeviceGuid=%@", tCheckTaskGuid,tDeviceGuid)
            }
        }else{
            if tDeviceGuid == "" {
                fetchRequest.predicate = NSPredicate(format: "tCheckTaskGuid=%@ and tNodeGuid=%@", tCheckTaskGuid,tNodeGuid)
            }else{
                fetchRequest.predicate = NSPredicate(format: "tCheckTaskGuid=%@ and tNodeGuid=%@ and tDeviceGuid=%@", tCheckTaskGuid,tNodeGuid,tDeviceGuid)
            }
        }
        
        let asyncFetchRecquest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result:NSAsynchronousFetchResult) in
            
            let fetchObjct = result.finalResult as! [Inspect_Device_Table]
            
            for model in fetchObjct{
                managedObectContext.delete(model)
            }
            appDelegate.saveContext()
        }
        do {
            try managedObectContext.execute(asyncFetchRecquest)
            return true
        }catch{
            return false
//            fatalError("刪除數(shù)據(jù)失敗")
        }
        
    }


   //刪除全部記錄
    func deleteAllData() {
       
        let fetchRequestDevice = NSFetchRequest<NSFetchRequestResult>(entityName: "Inspect_Device_Table")
       
        let asyncFetchDeviceRecquest = NSAsynchronousFetchRequest(fetchRequest: fetchRequestDevice) { (result:NSAsynchronousFetchResult) in
            
            let fetchObjct = result.finalResult as! [Inspect_Device_Table]
            
            for model in fetchObjct{
                managedObectContext.delete(model)
            }
            appDelegate.saveContext()
        }
        
        do {
            try managedObectContext.execute(asyncFetchDeviceRecquest)
            
        }catch{
            fatalError("刪除數(shù)據(jù)失敗")
        }
    }
}

這是我使用coredata的記錄,歡迎交流。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容