1. Establishment of CoreData Project
Tick User Core Data when creating a project
2. Create entities (Entity)
After you create the project, you can see that there is a. xcdatamodeld file in the directory. Open it and click the Add Entity button below to create a new entity. Here, I created the student corpse, and two attributes were created with the time data and first name. When you're done, click the show the Data Model Inspector Button, which has the name and class two options, which are the entity names and the class names to be generated.
When you are finished, select Menu Editor–>create nsmanagedobject Subclass ... You can complete the creation of the Studentmanagedobject entity.
The code is as follows:
import Foundationimport CoreData@objc(StudentManagedObject)class StudentManagedObject: NSManagedObject { @NSManaged var date: NSDate @NSManaged var name: String}
3. Create a model
Now that you have an entity, why do you create a model? This is based on layered design considerations, the previous step of the production of the entity is a subclass of Nsmanagedobject, from the level of consideration is the persistence layer. The persistence layer and the business layer, the presentation layer separation, will show a great advantage when the project logic is more complex . So I'm going to create a Studentmodel model that inherits NSObject, and the properties and Studentmanagedobject are exactly the same.
The code is as follows:
import UIKitclass StudentModel: NSObject { varString? vardate: NSDate?}
4. Create a Basedao base class
When the CoreData project is created, four parameters are automatically generated in the Appdelegate:
Applicationdocumentsdirectory This parameter is the path to the database file
Managedobjectmodel all entities or data structures of a database containing the definition information for each entity
Persistentstorecoordinator equivalent to database connection
Managedobjectcontext is managed object context, can be implemented in the context of the search, delete, insert and other operations, and finally need to synchronize
Although it seems complicated, the main use is the last managedobjectcontext.
The default parameters are in Appdelegeta, in order to build a unified database provider, we need to create a Basedao class, and then copy the four parameters in the past, all the database access DAO inherits this base class, so it can be easily called. The code is as follows:
////Basedao.swift//Coredatademo////Copyright (c) 2015 Worthy.zhang. All rights reserved.//Import Uikitimport Coredataclass Basedao:NSObject{//MARK:-Core Data StackLazy var applicationdocumentsdirectory:Nsurl= {//The directory the application uses to store the Core Data store file. This code uses a directory named "Com.worthy.CoreDataDemo" in the application ' s documents application support directory.
Let URLs =Nsfilemanager. Defaultmanager(). Urlsfordirectory(. Documentdirectory, Indomains:. Userdomainmask)returnUrls[urls. Count-1] As!Nsurl} () lazy var Managedobjectmodel:nsmanagedobjectmodel = {//The managed object model for the application. This property was 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")!returnNsmanagedobjectmodel (Contentsofurl:modelurl)! } () lazy var persistentstorecoordinator:nspersistentstorecoordinator? = {//The persistent store coordinator for the application. This implementation creates and return a coordinator, has added the store for the application to it. This property is optional since there was legitimate error conditions that could cause the creation of the store to fail.< /c0> //Create the Coordinator and storevar coordinator:nspersistentstorecoordinator? = Nspersistentstorecoordinator (Managedobjectmodel: Self. Managedobjectmodel) Let URL = Self. Applicationdocumentsdirectory. Urlbyappendingpathcomponent("Coredatademo.sqlite") var error:Nserror? =Nilvar Failurereason ="There is an error creating or loading the application ' s saved data." ifcoordinator!. Addpersistentstorewithtype(Nssqlitestoretype, configuration:Nil, Url:url, Options:Nil, error: &error) = =Nil{coordinator =Nil //Report any error we got.var dict = [String:anyobject] () dict[nslocalizeddescriptionkey] ="Failed to initialize the application ' saved data"Dict[nslocalizedfailurereasonerrorkey] = Failurereason Dict[nsunderlyingerrorkey] = Error Error =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 don't use the This function in a shipping application, although it could be useful during. NSLog("unresolved error \ (error), \ (error!. UserInfo) ") Abort ()}returnCoordinator} () lazy var managedobjectcontext:nsmanagedobjectcontext? = {//Returns The managed object context for the application (which are already bound to the persistent store coordinator For the application.) This property is optional since there was legitimate error conditions that could cause the creation of the context to fail .Let coordinator = Self. Persistentstorecoordinator ifCoordinator = =Nil{return Nil} var managedobjectcontext = Nsmanagedobjectcontext () managedobjectcontext. Persistentstorecoordinator= CoordinatorreturnManagedobjectcontext} ()}
5. Create a data Access object Studentdao
In Studentdao implementation of the student and other operations, the specific method code as follows, you need to pay attention to model Studentmodel and entity studentmanagedobject conversion.
Inquire:
Func findAll ()Nsmutablearray {println (self.applicationDocumentsDirectory.description) LetCXT = Self.managedobjectcontext LetEntitydescription = Nsentitydescription.entityforname ("Student",Inmanagedobjectcontext: cxt! ) LetRequest = Nsfetchrequest () request.entity = Entitydescriptionvar Error: Nserror? = Nilvar ListData: [Anyobject]? = Cxt?. Executefetchrequest (Request,Error: &error)var Reslistdata: Nsmutablearray = Nsmutablearray () forDatainchListData as! [Studentmanagedobject] {varentity = DatavarModel = Studentmodel () model.name = Entity.name Model.date = entity.date Reslistdata.addo Bject (model)}returnReslistdata}
New:
Func Insert (Student:studentmodel) {Let CXT = Self. ManagedobjectcontextLet entity = Nsentitydescription. Insertnewobjectforentityforname("Student", inmanagedobjectcontext:cxt!) as! Studentmanagedobject entity. Name= Student. Name! Entity. Date=NSDate() var error:Nserror? =Nil if( Self. Managedobjectcontext?. Save(&error)! =Nil) {println ("Insert succeeded") }Else{println ("Insert Failed") } }
Delete:
Func Remove (Student:studentmodel) { LetCTX = Self.managedobjectcontext LetEntitydescription = Nsentitydescription.entityforname ("Student", inmanagedobjectcontext:ctx!) Let Request= Nsfetchrequest ()Request. Entity = EntitydescriptionRequest. predicate = nspredicate (format:"date = =%@", student.Date!) VarError: Nserror? = Nil LetListdata:[anyobject]? = CTX?. Executefetchrequest (Request,Error: &Error) forDatainchListData as! [Studentmanagedobject] {CTX?. DeleteObject (data) var savingerror:nserror? = NilifCTX?. Save (&savingerror)! = Nil {println ("Delete succeeded") }Else{println ("Delete Failed") } } }
Modify:
Func Modify (Student:studentmodel) { LetCTX = Self.managedobjectcontext LetEntitydescription = Nsentitydescription.entityforname ("Student", inmanagedobjectcontext:ctx!) Let Request= Nsfetchrequest ()Request. Entity = EntitydescriptionRequest. predicate = nspredicate (format:"date = =%@", student.Date!) VarError: Nserror? = Nil LetListdata:[anyobject]? = CTX?. Executefetchrequest (Request,Error: &Error) forDatainchListData as! [Studentmanagedobject] {data.name = student.name! var savingerror:nserror? = NilifCTX?. Save (&savingerror)! = Nil {println ("modified successfully") }Else{println ("Modify Failed") } } }
Finally, the unique instance is returned by calling Shareddao.
private let sharedInstance = StudentDao()class StudentDao: BaseDao { class var sharedDao : StudentDao { return sharedInstance }......}
6.Demo Demo
By calling the four methods in the demo, the demo Studentdao a simple Delete-and-change operation.
Demo Address: Https://github.com/WorthyZhang/CoreDataDemo
Use CoreData in Swift to implement additions and deletions