1. Add the CoreData Library under link Binary with libraries for add build phases in the project.
2. Create a new file in the current project select Coredata-->datamodel, create a new data model, add entities to the model entity,entity is the corresponding table in SQLite, an entity corresponding to a table, there are multiple tables to add multiple entities, Then add the attribute to the entity attributes,attributes is the column in the SQLite table.
3. Right-clicking the new Coredata-->nsmanageobject Subclass,xcode in the current project will let you select the data model and entity of the NSMANAGEOBJCT subclass to be generated. That is, to generate the database and table corresponding to the object model, when added, the newly generated object model contains @dynamic tagged objects, which means that the object setter and getter methods are done manually.
4. Add a header to the source file using CoreData
#import <CoreData/CoreData.h>
Three objects are required for 5.CoreData use:
(1). Nsmanagedobjectcontext
(2). Nsmanagedobjectmodel
(3). Nspersistentstorecoordinator
Nsmanagedobjectcontext is the context in which data persistence is performed, and is specified when initializing Nsmanagedobjectcontext: Nspersistentstorecoordinator
Nspersistentstorecoordinator is a data persistence helper that needs to specify the type of data storage used when data is persisted: SQLite, XML, memory. Also specify the path and Nsmanagedobjectmodel
Nsmanagedobjectmodel is the object model
6. Add three properties to the source file:
@property (Strong, Nonatomic) Nsmanagedobjectcontext * coredatacontext; @property (Strong, nonatomic) Nsmanagedobjectmo del * Coredatamodel; @property (Strong, nonatomic) nspersistentstorecoordinator * coredatapersistent;
And for deferred load initialization:
-(Nsmanagedobjectmodel *) coredatamodel{if (_coredatamodel ==nil) {_coredatamodel = [[Nsmanagedobjectmodel al] LOC] Initwithcontentsofurl:[[nsbundle Mainbundle] urlforresource:@ "Resultsmodel" withextension:@ "MOMD"]; } return _coredatamodel;} -(Nspersistentstorecoordinator *) coredatapersistent{if (_coredatapersistent==nil) {_coredatapersistent = [[NS] Persistentstorecoordinator alloc] initwithmanagedobjectmodel:[self Coredatamodel]]; NSString * Path = [Nssearchpathfordirectoriesindomains (nsdocumentationdirectory, Nsuserdomainmask, YES) lastObject]; Nsurl * Pathurl = [Nsurl fileurlwithpath:[path stringbyappendingstring:@ "Resultsmodel.sqlite"]]; Nserror * error = NIL; Nspersistentstore * store = [_coredatapersistent addpersistentstorewithtype:nssqlitestoretype configuration:nil URL: Pathurl Options:nil Error:&error]; if (!store) {[NSException raise:@ "Add Database Error" format:@ "%@", [Error Localizeddescription]]; }} return _coredatapersistent;} -(Nsmanagedobjectcontext *) coredatacontext{if (_coredatacontext ==nil) {_coredatacontext = [[NSManagedObjec Tcontext alloc] Initwithconcurrencytype:nsmainqueueconcurrencytype]; [_coredatacontext setpersistentstorecoordinator:[self coredatapersistent]; } return _coredatacontext;}
Nsmanagedobjectmodel needs to specify the object model XXX.MOMD This is the new CoreData:xxx.xcdatamodeld generated automatically under the bundle.
Insert data:
Results * Insertresult = [nsentitydescription insertnewobjectforentityforname:@ "Results" Inmanagedobjectcontext: [ Self Coredatacontext]]; insertresult.in = @ "123"; Insertresult.re = @ "OK"; insertresult.red = @ "1"; NSDateFormatter * Dateformatter = [[NSDateFormatter alloc] init]; [Dateformatter setdateformat:@ "Yyyy-mm-dd hh:mm:ss"]; Insertresult.time = [dateformatter stringfromdate:[nsdate Date]]; Nserror * error = nil; if (![ [Self Coredatacontext] Save: &error]) { [nsexception raise:@ ' Save data to Database error: ' format:@ '%@ ', [ Error localizeddescription]]; }
Here's in. Re ReD. Time corresponds to the attribute in. Re. ReD of the entity results. When time is assigned to them, the call to [context Save:&error] is saved directly to the database.
Read data:
Nsfetchrequest * Databasefecth = [[Nsfetchrequest alloc] init]; databasefecth.entity = [nsentitydescription entityforname:@ "Results" Inmanagedobjectcontext:[self CoreDataContext]] ; Nsarray * OBJS = [[self coredatacontext] executefetchrequest:databasefecth error:&error]; if (Error) { [nsexception raise:@ "Fetch data from Database error:" format:@ "%@", [Error localizeddescription]]; } for (Nsmanagedobject * obj in Objs) { NSLog (@ "%@", obj); }
It is important to note that if you use _context instead of [self context] to get the context of the current object model, there will be an error at run time:
Terminating app due to uncaught exception ' nsinvalidargumentexception ', Reason: ' +entityforname:nil are not a legal NS Managedobjectcontext parameter searching for entity name ' Results '
Because the direct use of _context is nil, only the call will not be nil
iOS Development CoreData Use