在开发中经常会涉及到本地数据的存储。一般使用比较多的有,plist,本地文件,SQLite,coredata。根据要存储的数据类型选择对应的方法存储数据。在数据比较复杂时我选用coredata。最初使用原生的SQLite,修改比较麻烦,最后换成了coredata。操作步骤如下:
创建DataModel文件。
在DataModel中创建数据表,然后在数据表中创建对应的数据字段。
创建一个存储调度器,名字就是上面创建的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)")
}
}
}
为了方便操作,我们创建一个类用来添加,删除,修改,查询数据。
import Foundation
import CoreData
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObectContext = appDelegate.persistentContainer.viewContext
class CoreDataManager: NSObject {
//添加数据(添加的数据比较多时,可以使用模型)
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("数据保存成功")
return true
}catch{
print("数据保存失败")
return false
}
}
//查询数据
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)
}
}
// 执行请求
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("数据读取成功")
return deviceArray
} catch {
print("数据读取失败")
return deviceArray
}
}
//删除指定数据
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("删除数据失败")
}
}
//删除全部记录
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("删除数据失败")
}
}
}
这是我使用coredata的记录,欢迎交流。