IOS coredata additions and deletions to check the detailed _ios

Source: Internet
Author: User
Tags object model reserved

Recently in the study of CoreData, because the project development needs, deliberately learn and tidy up a bit, sorted out to facilitate later use and peer reference. Currently developing projects using the swift language development. So the swift version was sorted out and I gave up the OC. Although Swift3 already have, this version of the current collation is Swift2. Swift 3 has some new features. Additional adjustments are required, and there is a time to reorganize them later.

There are two ways of inheriting CoreData:

Integration when creating projects

This way is automatically inherited in the Appdelegate, the use of the call needs to be uiapplication to get appdelegate get conext. I do not like this way, do not like appdelegate too much code heap together, sorted out this way

Separate the CoreData inherited code into a single instance class

Project Structure Chart

Description of the project document
the CoreData core document is
1.XPStoreManager (Single case class for managing CoreData)
2.coredatademo.xcdatamodeld (coredata data Model file)
3.student+coredataproperites.swift and Student.swift (Student object)
4.viewcontroller.swift and Main.storyboard are sample code

Detail code

1. Xpstoremanager.swift
CoreData Data Management single case class

Xpstoremanager.swift//Coredatademo////Created by Xiaopin on 16/9/16. COPYRIGHT©2016 year xiaopin.cnblogs.com.

All rights reserved. Import coredata///Local Database management class: The default is written in Appdelegate, you can separate class Xpstoremanager {//single case writing static let Sharei Nstance = Xpstoremanager () private init () {}//MARK:-Core Data Stack lazy var applicationdocument Sdirectory: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:nsm Anagedobjectmodel = {//The managed object model for the application. This is not optional. It is a fatal error for the "Application not" 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 has added the store for the application to it.

  This was 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.managedO Bjectmodel) Let URL = self.applicationDocumentsDirectory.URLByAppendingPathComponent ("Singleviewcoredata.sqlite") v

  Ar Failurereason = "There is an error creating or loading the application ' s saved data." Do {try Coordinator.addpersistentstorewithtype (Nssqlitestoretype, Configuration:nil, Url:url, Options:nil)} CA tch {

   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 T

   He error appropriately. Abort () causes the application to generate a crash log and terminate.

   You are should not with this function in a shipping application and although it may is useful during development.

 

 NSLog ("unresolved error \ Wrappederror), \ (wrappederror.userinfo)") Abort ()} return Coordinator} () Lazy var managedobjectcontext:nsmanagedobjectcontext = {//Returns the managed object context for the application (WH The ICH is already bound to the persistent store coordinator for the application.) This is optional since there are legitimate error condItions that could cause the creation's 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 app

    Ropriately. Abort () causes the application to generate a crash log and terminate.

    You are should not with this function in a shipping application and although it may is useful during development.

 

Let Nserror = error as Nserror NSLog ("Unresolved error \ (nserror), \ (nserror.userinfo)") Abort ()}}

 }

2.appdelegate.swift

Add a code to the line number, exit and save

Func applicationwillterminate (application:uiapplication) {
  //called when the application was about to terminate. Save data if appropriate. Also applicationdidenterbackground:.
  Saves changes in the application ' s managed object context before the application terminates.
  XPStoreManager.shareInstance.saveContext ()

 }

3.student.swift

This paper compiles and revises the object of this student.

Student.swift//Coredatademo////Created by Cdmac on 16/9/12. COPYRIGHT©2016 year xiaopin.cnblogs.com.

All rights reserved. Import Foundation Import CoreData class Student:nsmanagedobject {//Insert code here to add functionality To your managed object subclass/* Generally related to the situation are: Add and change, single object query, paging query (all, conditional query, sorting), whether the object exists, batch increase, batch modification * *///judge whether the object exists, obj The parameter is the dictionary class of the current property Func Exsitsobject (obj:[string:string])-> Bool {//Get the context of the managed data Object-let contexts = Xpstoremanag Er.shareInstance.managedObjectContext//Declare a data request let Fetchrequest = Nsfetchrequest (entityname: "Student")/Group Filter parameters Let Stuid = obj["Stuid"] Let name = obj["name"]//mode one let predicate1 = nspredicate (format: "Stuid =

  %@ ", stuid!)

  Let Predicate2 = nspredicate (format: "name =%@", name!) Synthetic filtration conditions//or, and, not, meaning: or with the non, understand the database students should be very easy to understand let predicate = Nscompoundpredicate (orpredicatewithsubpredicates:

  [Predicate1,predicate2]) Let predicate = nscomPoundpredicate (andpredicatewithsubpredicates: [Predicate1,predicate2]) fetchrequest.predicate = predicate/Mode two

  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}///add object, obj parameter is Dictionary of current property class func InsertObject (obj: [string:string])-> Bool {//If object is present, returns if Exsitsobject (obj) {return FAL SE}//Get managed Data context object let contexts = XPStoreManager.shareInstance.managedObjectContext//Create student object let S Tu = Nsentitydescription.insertnewobjectforentityforname ("Student", Inmanagedobjectcontext:context) as ! Student//Object assignment let sexstr:string if obj["sex"] = = "Male"{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 = Numbe

  

  Rfmt.numberfromstring (obj["ClassId"]!) Save do {try Context.save () print (Save success!) ") return true} catch {FatalError (" Cannot Save: \ (Error) "} return false}///Delete object class Func Delete

  

  Object (obj:student)-> bool{//Get Managed data context objects let contexts = XPStoreManager.shareInstance.managedObjectContext Way one: For example, the list is already an object obtained from the database, directly calling the CoreData default Delete method Context.deleteobject (obj) XPStoreManager.shareInstance.saveCont  EXT ()//mode two: through the obj parameters such as: Id,name, through such a condition to query an object, delete this object from the database//code: Slightly return True}///update object class Func updateobject (obj:[string:string])-> Bool {//obj parameter description: The current object to update the field information, the unique flag is required, the other is optional properties letContext = XPStoreManager.shareInstance.managedObjectContext Let oid = obj["Stuid"] let student:student = Self.fe Tchobjectbyid (Int (oid!)!)! as! Student//traversal parameters, and then replace the corresponding parameters 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 ("If there are other parameters that need to be modified, like")}///Perform update operation do {try Context.save () print ("Update succeeded!") ") return true} catch {FatalError (" Cannot Save: \ (Error) "} return False}///query object class func F Etchobjects (Pageindex:int, Pagesize:int)-> [Anyobject]? {//Get Managed Data context object let contexts = XPStoreManager.shareInstance.managedObjectContext//Declaration data request Let Fetchreque St:nsfetchrequest = Nsfetchrequest (entityname: "Student") Fetchrequest.fetchlimit = pageSize//per page size Fetchrequest.fet Choffset = PageiNdex * pageSize//First page//Set query criteria: Reference exsitsobject//let predicate = nspredicate (format: "id= ' 1 '", "")//fetchre 

  Quest.predicate = predicate//Set sort//by Student ID Descending let Stuidsort = Nssortdescriptor (key: "Stuid", Ascending:false) By name ascending let Namesort = Nssortdescriptor (key: "Name", ascending:true) let sortdescriptors:[nssortdescriptor] = [Stuidsort,namesort] fetchrequest.sortdescriptors = sortdescriptors//query operation do {let FETCHEDOBJECTS:[ANYOB Ject]? = Try Context.executefetchrequest (fetchrequest)//Traverse Query Results/* 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 FE Tchedobjects} catch {FatalError ("Cannot Save: \ (Error)"} return nil}///an object class based on ID query func Hobjectbyid (oId:int)-> Anyobject? {//Get context object let contexts = XPStoreManager.shareInstance.managedObjectContext//Create Query object let Fetchrequest: Nsfetchrequest = Nsfetchrequest (entityname: "Student")//Construction parameter fetchrequest.predicate = nspredicate (format: "Stui D =%@ ", String (OID))//execute code and return result do{let results:[anyobject]? = Try Context.executefetchrequest (fetchreques T) if results? Count > 0 {return results![

 0]}}catch{fatalerror ("query when an object fatal error: \ (Error)")} Return nil}}

4.viewcontroller.swift

Specific use:

Viewcontroller.swift//Coredatademo////Created by Cdmac on 16/9/11. COPYRIGHT©2016 year Pinguo.

All rights reserved. Import Uikit Let Cellidentifiler = "Reusecell" class Viewcontroller:uiviewcontroller {@IBOutlet weak VA

 R 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 all additional setup after loading the view, typically from

  A nib. Self.dataarray = student.fetchobjects (0, pagesize:20) self.tableView.reloadData ()} override Func Didreceivemem

 Orywarning () {super.didreceivememorywarning ()//Dispose of any of the can is 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 ("Add success") 

  Self.dataarray = student.fetchobjects (0,pagesize:20) self.tableView.reloadData ()}else{print ("Add failed") } @IBAction func updateaction (sender:anyobject) {var dic = [string:string] () dic["stuid"] = t Xtno.text dic["Name" = txtName.Text//dic["Sex" = Txtsex.text dic["classId"] = Txtclassid.text if Studen T.updateobject (DIC) {print ("Update succeeded") Self.dataarray = Student.fetchobjects (0,pagesize:20) Self.tableview. Reloaddata ()}else{print (update failed)}}} extension Viewcontroller:uitableviewdelegate,uitableviewda tasource{//Table How many groups func Numberofsectionsintableview (Tableview:uitableview)-> Int {return 1}//Group how many Row func TableView (Tableview:uitableview, numberofrowsinsection section:int)-> Int {if Self.dataarray!= Nil p;& Self.dataarray?Count > 0 {return self.dataarray!. Count} return 0}//height func tableview (tableview:uitableview, Heightforrowatindexpath Indexpath:nsindexpa TH)-> CGFloat {return 50}//Cell Gegacay func tableview (Tableview:uitableview, Cellforrowatindexpath Indexpath : Nsindexpath)-> UITableViewCell {Let cell = Tableview.dequeuereusablecellwithidentifier (Cellidentifiler) L ET 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 = "Male" if stu.sex? Intvalue!= 1 {sexstr = "female"} Label1.Text = "\ (stu.stuid!) \ (stu.name!)

  \ (SEXSTR) \ (stu.classid!) "

 Label2.Text = "Http://xiaopin.cnblogs.com" return cell! ///select Func TableView (Tableview:uitableview, Didselectrowatindexpath indexpath:nsindexpath) {} func t Ableview (Tableview:uitableview, CaneditrowatinDexpath Indexpath:nsindexpath)-> Bool {return true} func TableView (Tableview:uitableview, commiteditings Tyle Editingstyle:uitableviewcelleditingstyle, Forrowatindexpath indexpath:nsindexpath) {if EditingStyle = =. Delete {//Get current object let Student:student = self.dataarray![ Indexpath.row] As! Student//delete local storage student.deleteobject (Student)//Refresh data source Self.dataarray?. Removeatindex (indexpath.row)//self.dataarray = student.fetchobjects (0, pagesize:20)//Delete cell TABLEVIEW.D Eleterowsatindexpaths ([Indexpath], withrowanimation:. Automatic)}} func TableView (Tableview:uitableview, Editingstyleforrowatindexpath Indexpath:nsindexpath) ; Uitableviewcelleditingstyle {return. Delete} func TableView (Tableview:uitableview, Titlefordeleteconfirmationbuttonforrowatindexpath Indexpath:nsinde XPath)-> String?

 {return ' delete '}}

Run Effect chart

SOURCE Download: Coredatademo.zip

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.