In the last word, we define the variables and methods related to CoreData, and do the preparatory work, so we can try to succeed. First open the previous message generated in the Info class, in which to reference the header file in the place to add a @objc (Info), or the subsequent error, I do not know why.
Then add the following code in the Viewcontroller code to implement:
Import Uikitimport coredataclass Viewcontroller:uiviewcontroller {var tempinfo:info! Override Func Viewdidload () {super.viewdidload () if Let Managementcontext = (uiapplication.sharedapplicatio N (). Delegate as Appdelegate). managedobjectcontext{Tempinfo = Nsentitydescription.insertnewobjectforenti Tyforname ("info", Inmanagedobjectcontext:managementcontext) as Info//equals to info, can be assigned operation T Empinfo.name = "CG" tempinfo.location = "Xidian"//Remember save Var e:nserror? If Managementcontext.save (&e) = true {println ("Insert error \ (e!. localizeddescription)} if let Managementcontext = (uiapplication.sharedap Plication (). Delegate as Appdelegate). managedobjectcontext{var fetchrequest = nsfetchrequest (entityname: "I NFO ") var result = Managementcontext.execUtefetchrequest (fetchrequest, Error: &e) as [Info] if E! = Nil { println ("Fetch result error: \ (e!). Localizeddescription)} else {for item:anyobject in result { Let temp = Item as Info println ("Name: \ (temp.name), localtion: \ (temp.location)") } } } } }}The function of the above code is through the proxy way, first insert the value of an instance to info, the Name property is Cg,location property is Xidian, then query, print out, run after the console display as follows:
With insert and query, the following implements the update operation, adding the following code in the code above:
If let Managementcontext = (Uiapplication.sharedapplication (). Delegate as Appdelegate). managedobjectcontext { var Fetchrequest = Nsfetchrequest (entityname: "Info") fetchrequest.predicate = nspredicate (format: "name = ' CG '", Argumentarray:nil) var result = managementcontext.executefetchrequest (fetchrequest, Error: &e) as [Info] If E! = nil { println ("Fetch result error: \ (e!). localizeddescription) } else {for item:anyobject in result {let temp = Item as Info temp.name = "Cggg GG " println (" Name: \ (temp.name), localtion: \ (temp.location) ") } managementcontext.save (&e) } }
The function of the above code is to change the name of the instance of CG to CGGGGG, the result of the operation is as follows:
Now to implement the delete operation, similar to the update operation, on the basis of the update code to change the name of the code to:
Managementcontext.deleteobject (temp)
Just fine, now we try to delete the record named CGGGGG, you can see that CGGGGG is gone, in this can't everyone try.
Swift language IOS8 development war record Core DATA3