1 Import UIKit2 Import CoreData3 4 //CoreData Manager5 classCoredatamanager:nsobject {6 7 //Single Case8 StaticLet Sharedmanager:coredatamanager =Coredatamanager ()9 Ten //Privatization Constructors One Override Privateinit () { A Super.init () - } - the //persistence container, can provide management context - //IOS10 introduced, in order to be compatible with the low version, we set up here private, no longer use, manually implement the management object context, see the next property - //contains all the core objects in Coredatastack, the following are three important objects - //Viewcontext:nsmanagedobjectcontext-management context, primarily responsible for data manipulation + //Managedobjectmodel:nsmanagedobjectmodel-Manage Object Model - //Persistentstorecoordinator:nspersistentstorecoordinator + PrivateLazy var persistentcontainer:nspersistentcontainer? = { A at //the core objects of CoreData are not thread-safe. - //ensure thread safety with synchronous/mutex locks - Objc_sync_enter (self) - //instantiating an object, you need to specify the data model - //specified name = = Name of the data model = = name of the database in the sandbox - //Let container = Nspersistentcontainer (name: "demo_db") in - //Manage object model, parameters pass in nil, automatically merge all data models in Mainbundle toLet model = Nsmanagedobjectmodel.mergedmodel (FROM:NIL)! + - //instantiating a persisted container the //parameter one: database name * //parameter two: the merged model $var container:nspersistentcontainer? = Nspersistentcontainer (Name:"ys.db", Managedobjectmodel:model)Panax Notoginseng - the //"synchronous mode" load "persistent storage"--the essence is to open/new/Modify the database (synchronous mode, ensure thread safety) +Container?. Loadpersistentstores (Completionhandler: {(storedescription, error)inch A //To determine if the database was created with errors the ifLet error = Error asNserror? { + /* - Common errors: $ 1, directory does not exist, or write forbidden, unable to create database file $ 2. Insufficient storage space for equipment - 3. Persistent storage cannot be accessed due to data protection when the permission or device is locked - 4. The database cannot be migrated to the current model version the */ -Print"Open/New/Modify Database error: \ (Error)")Wuyicontainer =Nil the } - }) Wu - objc_sync_exit (self) About $ returnContainer - }() - - //Managing Object Contexts ALazy var moc:nsmanagedobjectcontext? = { + //Synchronous lock/Mutex protection the objc_sync_exit (self) - $ //instantiating the management context thevar mocobj:nsmanagedobjectcontext? =Nsmanagedobjectcontext (concurrencytype:. Mainqueueconcurrencytype) the the //instantiating an object model theLet Momobj = Nsmanagedobjectmodel.mergedmodel (from:nil)! - in //Persistent Storage Scheduler theLet PSC =nspersistentstorecoordinator (managedobjectmodel:momobj) the About //Add a database the //parameter 1: Data storage type the //Parameter 3: Save the URL of the SQLite database file the //parameter 4: Set database Options +Let Cachedir = Nssearchpathfordirectoriesindomains (. Cachesdirectory,. Userdomainmask,true). last! -Let Path = (cachedir asNSString). Appendingpathcomponent ("ys.db") theLet dict = [nsmigratepersistentstoresautomaticallyoption:true,BayiNsinfermappingmodelautomaticallyoption:true] the theLet PersistentStore =Try?Psc.addpersistentstore (Oftype:nssqlitestoretype, Configurationname:nil, At:url (fileurlwithpath:path), options : dict) - - ifPersistentStore! =nil{ the //specifying the storage scheduler for the management context theMocobj?. Persistentstorecoordinator =PSC the } the Else{ -Print"Error opening/new/modifying Database") theMocobj =Nil the } the 94 objc_sync_exit (self) the the returnMocobj the }()98 About //Save Context - func Savecontext () {101 ifLet context =moc{102 //transactions: You can save multiple data, not necessarily every time the data changes need to save, can be saved at once103 ifContext.haschanges {104 Do { the TryContext.save ()106}Catch {107Let Nserror = Error asNserror108Print"Error saving data: \ (nserror)")109 } the }111 } the }113}
Version Coredatamanager-swift-compatible with previous versions of IOS10