When the General Program app is upgraded, the database may change, such as adding table fields, adding tables, etc. There are two things at this point:
The first is to simply delete the local old database directly, re-establish the new database, and the second is to migrate the database and update the database. The first case is a simple rough type, but does not retain any historical data and is generally not recommended for use. Here is the second case, divided into four steps: The first step, on the code, the main red font of the place
-(Nspersistentstorecoordinator *) persistentstorecoordinator
{
if (_persistentstorecoordinator! = nil) {
return _persistentstorecoordinator;
}
Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager];
NSString *folderpath = [NSString stringwithformat:@ "%@/calendar", [Nssearchpathfordirectoriesindomains ( NSDocumentDirectory, Nsuserdomainmask, YES) Lastobject]];
if (![ FileManager Fileexistsatpath:folderpath]) {//If not present, this is the first time this program is run, then set up this folder
[FileManager Createdirectoryatpath:folderpath withintermediatedirectories:yes Attributes:nil Error:nil];
}
Nsurl *storeurl = [Nsurl fileurlwithpath:[folderpath stringbyappendingpathcomponent:@ "Calendar.sqlite"]];
nsdictionary *options = [nsdictionary dictionarywithobjectsandkeys:
[NSNumber Numberwithbool:yes],
Nsmigratepersistentstoresautomaticallyoption,
[NSNumber Numberwithbool:yes],
Nsinfermappingmodelautomaticallyoption, nil];
Nserror *error = nil;
_persistentstorecoordinator = [[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:[self Managedobjectmodel]];
if (![ _persistentstorecoordinatoraddpersistentstorewithtype:nssqlitestoretype configuration:nil URL:storeURL Options: options Error:&error]) {
NSLog (@ "unresolved error%@,%@", error, [error userInfo]);
Abort ();
}
return _persistentstorecoordinator;
}
Step Two: add a new version of the data model
Select Calendar.xcdatamodel File Click Editor, ADD model version to pop up a dialog box that fills in version Name (such as Calendar 2) and based on Model (such as Calen DAR).
Step three: Continue to select the Calendar.xcdatamodel file, press OPTION + COMMAND + 0 key to open the right side of Xcode, select Calendar 2 in the current of model version.
Fourth step: Modify your Calendar 2.xcdatamodel file (such as new fields, add tables, etc.), and then remember to update the entity code of your ALTER TABLE. (Note: This sequence of steps must be aware that you must not directly modify the table structure on the original Calendar.xcdatamodeld, and then add a new version, so that will always error)
Ps:nsurl *storeurl = [Nsurl fileurlwithpath:[folderpath stringbyappendingpathcomponent:@ "Calendar.sqlite"]]; This is still calendar.sqlite, not calendar 2.sqlite, as Calendar 2 has been selected in the third step.
OK, start the build.
CoreData database updates, data migration