Some finishing on core data (iii)
The relationship between the four types of core Data stacks and their relationships is as follows:
- Nsmanagedobjectmodel
- Nspersistentstore
- Nspersistentstorecoordinator
- Nsmanagedobjectcontext
Handwritten core Data Stack, the new file inherits NSObject, and in which three objects are initialized in sequence:,, NSManagedObjectContext
NSPersistentStoreCoordinator
NSManagedObjectModel
The specific code is implemented as follows:
1 //CoreDataStack.h2 3 #import<Foundation/Foundation.h>4 #import<CoreData/CoreData.h>5 6 @interfaceCoredatastack:nsobject7 8@property (nonatomic, strong) Nsmanagedobjectcontext *context;9 Ten- (void) Savecontext; One A @end - - //COREDATASTACK.M the - #import "CoreDataStack.h" - - @interfaceCoredatastack () + -@property (nonatomic, strong) Nspersistentstorecoordinator *PSC; +@property (nonatomic, strong) Nsmanagedobjectmodel *Managedobjectmodel; A at @end - - @implementationCoredatastack - - @synthesizeManagedobjectmodel =_managedobjectmodel; - in- (void) Savecontext { - if(_context) { toNserror *error =Nil; + if([_context haschanges] && [_context save:&ERROR]) { -NSLog (@"%@", error.localizeddescription); the abort (); * } $ }Panax Notoginseng } - the-(Nsurl *) Applicationdocumentsdirectory { +Nsarray *array =[[Nsfilemanager Defaultmanager] urlsfordirectory:nsdocumentdirectory indomains:nsuserdomainmask]; A returnArray.lastobject; the } + --(Nsmanagedobjectcontext *) Context { $ if(_context) { $ return_context; - } -_context =[[Nsmanagedobjectcontext alloc] initwithconcurrencytype:nsmainqueueconcurrencytype]; the [_context setpersistentstorecoordinator:[self PSC]]; - return_context;Wuyi } the --(Nspersistentstorecoordinator *) PSC { Wu if(_PSC) { - return_PSC; About } $_PSC =[[Nspersistentstorecoordinator alloc] initwithmanagedobjectmodel:[self Managedobjectmodel]]; -Nsurl *url = [[Self applicationdocumentsdirectory] urlbyappendingpathcomponent:@"Jmdog_walk.sqlite"]; -[_PSC addpersistentstorewithtype:nssqlitestoretype Configuration:nil Url:url options:@{ nsmigratepersistentstoresautomaticallyoption:@1} Error:nil]; - return_PSC; A } + the-(Nsmanagedobjectmodel *) Managedobjectmodel { - if(_managedobjectmodel) { $ return_managedobjectmodel; the } theNsurl *url = [[NSBundle mainbundle] Urlforresource:@"Jmdog_walk"Withextension:@"MOMD"]; the_managedobjectmodel =[[Nsmanagedobjectmodel alloc] initwithcontentsofurl:url]; the return_managedobjectmodel; - } in the @end
The places to be noted are:
- All global variables are lazy loaded, improving efficiency;
- Just put it
NSManagedObjectContext
in the. h to go;
- Call Addpersistentstorewithtype: Note that the database file is named as the type of the SQLite suffix, otherwise it will be an error;
- Note that the naming consistency is used in the code
JMDog_Walk
, and when you build the core data file, you also name the file JMDog_Walk
!
Some finishing on core data (iii)