欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS CoreData 增删改查详解

程序员文章站 2023-12-15 15:05:04
最近在学习coredata, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴。目前开发使用的swift语言开发的项目。所以整理出来的是swift版...

最近在学习coredata, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴。目前开发使用的swift语言开发的项目。所以整理出来的是swift版本,oc我就放弃了。 虽然swift3 已经有了,目前整理的这个版本是swift2 的。swift 3 的话有些新特性。 需要另外调整,后续有时间再整理。 

继承coredata有两种方式: 

创建项目时集成

iOS CoreData 增删改查详解 

这种方式是自动继承在appdelegate里面,调用的使用需要通过uiapplication的方式来获取appdelegate得到conext。本人不喜欢这种方式,不喜欢appdelegate太多代码堆在一起,整理了一下这种方式

将coredata继承的代码单独解耦出来做一个单例类 

项目结构图

iOS CoreData 增删改查详解 

项目文件说明 
coredata核心的文件就是 
1.xpstoremanager(管理coredata的单例类) 
2.coredatademo.xcdatamodeld (coredata数据模型文件)
 3.student+coredataproperites.swift和student.swift (学生对象) 
4.viewcontroller.swift 和main.storyboard是示例代码

iOS CoreData 增删改查详解

细节代码 

1. xpstoremanager.swift
coredata数据管理单例类

//

// xpstoremanager.swift

// coredatademo

//

// created by xiaopin on 16/9/16.

// copyright © 2016年 xiaopin.cnblogs.com. all rights reserved.

//

 

import coredata

 

/// 本地数据库管理类:默认是写在appdelegate的,可以这样分离出来

class xpstoremanager {

 

 //单例写法

 static let shareinstance = xpstoremanager()

 

 private init() {

  

 }

 

 // 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.pinguo.coredatademo" in the application's documents application support directory.

  let urls = nsfilemanager.defaultmanager().urlsfordirectory(.documentdirectory, indomains: .userdomainmask)

  print("\(urls[urls.count-1])")

  return urls[urls.count-1]

 }()

 

 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.

  let modelurl = nsbundle.mainbundle().urlforresource("coredatademo", withextension: "momd")!

  return nsmanagedobjectmodel(contentsofurl: 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.urlbyappendingpathcomponent("singleviewcoredata.sqlite")

  var failurereason = "there was an error creating or loading the application's saved data."

  do {

   try coordinator.addpersistentstorewithtype(nssqlitestoretype, configuration: nil, url: url, options: nil)

  } catch {

   // report any error we got.

   var dict = [string: anyobject]()

   dict[nslocalizeddescriptionkey] = "failed to initialize the application's saved data"

   dict[nslocalizedfailurereasonerrorkey] = failurereason

   

   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()

   }

  }

 }

 

}

2.appdelegate.swift 

在这个行数中加入一句代码,退出后执行保存一下

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.
  xpstoremanager.shareinstance.savecontext()

 }

3.student.swift 

编写了针对这个学生对象的增删改查 

//

// student.swift

// coredatademo

//

// created by cdmac on 16/9/12.

// copyright © 2016年 xiaopin.cnblogs.com. all rights reserved.

//

 

import foundation

import coredata

 

class student: nsmanagedobject {

 // insert code here to add functionality to your managed object subclass

 /*

  一般涉及到的情况有:增删改,单对象查询,分页查询(所有,条件查询,排序),对象是否存在,批量增加,批量修改

  */

 

 /// 判断对象是否存在, obj参数是当前属性的字典

 class func exsitsobject(obj:[string:string]) -> bool {

  

  //获取管理数据对象的上下文

  let context = xpstoremanager.shareinstance.managedobjectcontext

  //声明一个数据请求

  let fetchrequest = nsfetchrequest(entityname: "student")

  

  //组合过滤参数

  let stuid = obj["stuid"]

  let name = obj["name"]

  

  //方式一

  let predicate1 = nspredicate(format: "stuid = %@", stuid!)

  let predicate2 = nspredicate(format: "name = %@", name!)

  //合成过滤条件

  //or ,and, not , 意思是:或与非,懂数据库的同学应该就很容易明白

  let predicate = nscompoundpredicate(orpredicatewithsubpredicates: [predicate1,predicate2])

  //let predicate = nscompoundpredicate(andpredicatewithsubpredicates: [predicate1,predicate2])

  fetchrequest.predicate = predicate

  

  //方式二

  //fetchrequest.predicate = nspredicate(format: "stuid = %@ or name = %@", stuid!, name!)

  //fetchrequest.predicate = nspredicate(format: "stuid = %@ and name = %@", stuid!, name!)

  

  do{

   let fetchobjects:[anyobject]? = try context.executefetchrequest(fetchrequest)

   

   return fetchobjects?.count > 0 ? true : false

  }catch {

   fatalerror("exsitsobject \(error)")

  }

  

  return false

 }

 

 /// 添加对象, obj参数是当前属性的字典

 class func insertobject(obj: [string:string]) -> bool {

  

  //如果存在对象了就返回

  if exsitsobject(obj) {

   return false

  }

  

  //获取管理的数据上下文 对象

  let context = xpstoremanager.shareinstance.managedobjectcontext

  

  //创建学生对象

  let stu = nsentitydescription.insertnewobjectforentityforname("student",

                  inmanagedobjectcontext: context) as! student

 

  //对象赋值

  let sexstr:string

  if obj["sex"] == "男"{

   sexstr = "1"

  }else{

   sexstr = "0"

  }

  let numberfmt = nsnumberformatter()

  numberfmt.numberstyle = .nostyle

  stu.stuid = numberfmt.numberfromstring(obj["stuid"]!)

  stu.name = obj["name"]

  stu.createtime = nsdate()

  stu.sex = numberfmt.numberfromstring(sexstr)

  stu.classid = numberfmt.numberfromstring(obj["classid"]!)

  

  //保存

  do {

   try context.save()

   print("保存成功!")

   return true

  } catch {

   fatalerror("不能保存:\(error)")

  }

  return false

 }

 

 /// 删除对象

 class func deleteobject(obj:student) -> bool{

  

  //获取管理的数据上下文 对象

  let context = xpstoremanager.shareinstance.managedobjectcontext

  

  //方式一: 比如说列表已经是从数据库中获取的对象,直接调用coredata默认的删除方法

  context.deleteobject(obj)

  xpstoremanager.shareinstance.savecontext()

  

  //方式二:通过obj参数比如:id,name ,通过这样的条件去查询一个对象一个,把这个对象从数据库中删除

  //代码:略

  

  return true

 }

 

 /// 更新对象

 class func updateobject(obj:[string: string]) -> bool {

  //obj参数说明:当前对象的要更新的字段信息,唯一标志是必须的,其他的是可选属性

  let context = xpstoremanager.shareinstance.managedobjectcontext

  

  let oid = obj["stuid"]

  let student:student = self.fetchobjectbyid(int(oid!)!)! as! student

  

  //遍历参数,然后替换相应的参数

  let numberfmt = nsnumberformatter()

  numberfmt.numberstyle = .nostyle

  

  for key in obj.keys {

   switch key {

   case "name":

    student.name = obj["name"]

   case "classid":

    student.classid = numberfmt.numberfromstring(obj["classid"]!)

   default:

    print("如果有其他参数需要修改,类似")

   }

  }

  

  //执行更新操作

  do {

   try context.save()

   print("更新成功!")

   return true

  } catch {

   fatalerror("不能保存:\(error)")

  }

  

  return false

 }

 

  /// 查询对象

 class func fetchobjects(pageindex:int, pagesize:int) -> [anyobject]? {

  //获取管理的数据上下文 对象

  let context = xpstoremanager.shareinstance.managedobjectcontext

  

  //声明数据的请求

  let fetchrequest:nsfetchrequest = nsfetchrequest(entityname: "student")

  fetchrequest.fetchlimit = pagesize //每页大小

  fetchrequest.fetchoffset = pageindex * pagesize //第几页

  

  //设置查询条件:参考exsitsobject

  //let predicate = nspredicate(format: "id= '1' ", "")

  //fetchrequest.predicate = predicate

  

  //设置排序

  //按学生id降序

  let stuidsort = nssortdescriptor(key: "stuid", ascending: false)

  //按照姓名升序

  let namesort = nssortdescriptor(key: "name", ascending: true)

  let sortdescriptors:[nssortdescriptor] = [stuidsort,namesort]

  fetchrequest.sortdescriptors = sortdescriptors

  

  //查询操作

  do {

   let fetchedobjects:[anyobject]? = try context.executefetchrequest(fetchrequest)

   

   //遍历查询的结果

   /*

   for info:student in fetchedobjects as! [student]{

    print("id=\(info.stuid)")

    print("name=\(info.name)")

    print("sex=\(info.sex)")

    print("classid=\(info.classid)")

    print("createtime=\(info.createtime)")

    print("-------------------")

    

   }

    */

   return fetchedobjects

  }

  catch {

   fatalerror("不能保存:\(error)")

  }

  return nil

 }

 

  /// 根据id查询当个对象

 class func fetchobjectbyid(oid:int) -> anyobject?{

  

  //获取上下文对象

  let context = xpstoremanager.shareinstance.managedobjectcontext

  

  //创建查询对象

  let fetchrequest:nsfetchrequest = nsfetchrequest(entityname: "student")

  

  //构造参数

  fetchrequest.predicate = nspredicate(format: "stuid = %@", string(oid))

  

  //执行代码并返回结果

  do{

   let results:[anyobject]? = try context.executefetchrequest(fetchrequest)

   

   if results?.count > 0 {

    return results![0]

   }

  }catch{

   fatalerror("查询当个对象致命错误:\(error)")

  }

  

  return nil

 }

}

4.viewcontroller.swift 

具体使用: 

//

// viewcontroller.swift

// coredatademo

//

// created by cdmac on 16/9/11.

// copyright © 2016年 pinguo. all rights reserved.

//

 

import uikit

 

let cellidentifiler = "reusecell"

 

class viewcontroller: uiviewcontroller {

 @iboutlet weak var txtno: uitextfield!

 @iboutlet weak var txtname: uitextfield!

 @iboutlet weak var txtsex: uitextfield!

 @iboutlet weak var txtclassid: uitextfield!

 @iboutlet weak var tableview: uitableview!

 var dataarray:[anyobject]?

 

 override func viewdidload() {

  super.viewdidload()

  // do any additional setup after loading the view, typically from a nib.

  self.dataarray = student.fetchobjects(0, pagesize: 20)

  self.tableview.reloaddata()

 }

 

 override func didreceivememorywarning() {

  super.didreceivememorywarning()

  // dispose of any resources that can be recreated.

 }

 

 

 @ibaction func addaction(sender: anyobject) {

 

  var dic = [string:string]()

  

  dic["stuid"] = txtno.text

  dic["name"] = txtname.text

  dic["sex"] = txtsex.text

  dic["classid"] = txtclassid.text

  

  if student.insertobject(dic) {

   print("添加成功")

   self.dataarray = student.fetchobjects(0,pagesize: 20)

   

   self.tableview.reloaddata()

  }else{

   print("添加失败")

  }

 }

 

 @ibaction func updateaction(sender: anyobject) {

  

  var dic = [string:string]()

  

  dic["stuid"] = txtno.text

  dic["name"] = txtname.text

  //dic["sex"] = txtsex.text

  dic["classid"] = txtclassid.text

  

  if student.updateobject(dic) {

   print("更新成功")

   self.dataarray = student.fetchobjects(0,pagesize: 20)

   

   self.tableview.reloaddata()

  }else{

   print("更新失败")

  }

  

 }

 

}

 

extension viewcontroller:uitableviewdelegate,uitableviewdatasource{

 

 //表格有多少组

 func numberofsectionsintableview(tableview: uitableview) -> int {

  return 1

 }

 

 //每组多少行

 func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int {

  if self.dataarray != nil && self.dataarray?.count > 0 {

   return self.dataarray!.count

  }

  return 0

 }

 

 //高度

 func tableview(tableview: uitableview, heightforrowatindexpath indexpath: nsindexpath) -> cgfloat {

  return 50

 }

 

 //单元格加载

 func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell {

  let cell = tableview.dequeuereusablecellwithidentifier(cellidentifiler)

  

  let stu:student = self.dataarray![indexpath.row] as! student

  

  let label1:uilabel = cell?.contentview.viewwithtag(10001) as! uilabel

  let label2:uilabel = cell?.contentview.viewwithtag(10002) as! uilabel

  var sexstr = "男"

  if stu.sex?.intvalue != 1 {

   sexstr = "女"

  }

  label1.text = "\(stu.stuid!) \(stu.name!) \(sexstr) \(stu.classid!)"

  label2.text = "http://xiaopin.cnblogs.com"

  

  return cell!

 }

 

 //选中

 func tableview(tableview: uitableview, didselectrowatindexpath indexpath: nsindexpath) {

  

 }

 

 func tableview(tableview: uitableview, caneditrowatindexpath indexpath: nsindexpath) -> bool {

  return true

 }

 

 func tableview(tableview: uitableview, commiteditingstyle editingstyle: uitableviewcelleditingstyle, forrowatindexpath indexpath: nsindexpath) {

  if editingstyle == .delete {

   //获取当前对象

   let student:student = self.dataarray![indexpath.row] as! student

   

   //删除本地存储

   student.deleteobject(student)

   

   //刷新数据源

   self.dataarray?.removeatindex(indexpath.row)

   //self.dataarray = student.fetchobjects(0, pagesize: 20)

   

   //删除单元格

   tableview.deleterowsatindexpaths([indexpath], withrowanimation: .automatic)

  }

 }

 

 func tableview(tableview: uitableview, editingstyleforrowatindexpath indexpath: nsindexpath) -> uitableviewcelleditingstyle {

  return .delete

 }

 

 func tableview(tableview: uitableview, titlefordeleteconfirmationbuttonforrowatindexpath indexpath: nsindexpath) -> string? {

  return "删除"

 }

}

运行效果图

iOS CoreData 增删改查详解 

源码下载:coredatademo.zip

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: