Migrate core data to add new attribute - core-data

I have added new attribute and I need to migrate core data. As a result, I do like this.
Bus.xcDataModel >> Add model version
Then, I add new attribute. I change persistent store coordinator option as well like this.
#{NSMigratePersistentStoresAutomaticallyOption:#YES, NSInferMappingModelAutomaticallyOption:#YES}
But when I add that new attribute, it show me like this. How shall I do?
-[BusService setBus_wap:]: unrecognized selector sent to instance 0x1742a7320
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator_busservice
{
if (_persistentStoreCoordinator_busservice != nil)
return _persistentStoreCoordinator_busservice;
NSURL *applicationDocumentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *storeURL = [applicationDocumentsDirectory URLByAppendingPathComponent:#"Busservice_new.sqlite"];
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]] &&
!self.preloadEnabled)
{
NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"Busservice_new" ofType:#"sqlite"]];
NSError* err = nil;
if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err])
DLog(#"Oops, could not copy preloaded data");
}
NSError *error = nil;
_persistentStoreCoordinator_busservice = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator_busservice addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:#{NSMigratePersistentStoresAutomaticallyOption:#YES, NSInferMappingModelAutomaticallyOption:#YES} error:&error])
{
DLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator_busservice;
}

From that error it looks like you added a new attribute to your BusService entity in Core Data, but did not add the attribute to your BusService class. If you want to use accessor methods for this new attribute, you need to update the class as well. Or you can leave the class alone but use setValue:forKey: to assign values to the new attribute.

Related

This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation

I am creating an application using Microsoft Azure web service. On clicking logout button I need to clear my local core data base completely and all data will be reloaded after logging in again using the same username and password. To delete core data I am using below method
- (void) resetApplicationModel {
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = delegate.managedObjectContext;
for (NSPersistentStore *store in delegate.persistentStoreCoordinator.persistentStores) {
NSError *error;
NSURL *storeURL = store.URL;
NSLog(#"storeURL: %#", storeURL);
NSPersistentStoreCoordinator *storeCoordinator = delegate.persistentStoreCoordinator;
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
NSLog(#"There are errors: %#", error);
}
delegate.persistentStoreCoordinator = nil;
context = nil;
delegate.managedObjectModel = nil;
}
This is deleting all my data but when I am trying to login again without closing the application it is giving me following error
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation.'
This is occurring because while deleting data I am setting persistentStoreCoordinator to nil and its instance is being created inside AppDelegate file. Can somebody suggest me any solution for this?
Thanks for help in advance,.
Your code has a number of errors.
Regardless, to achieve what you need, try this modified version of your method resetApplicationModel...
- (void) resetApplicationModel {
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
// NSManagedObjectContext *context = delegate.managedObjectContext;
for (NSPersistentStore *store in delegate.persistentStoreCoordinator.persistentStores) {
NSError *error;
NSURL *storeURL = store.URL;
NSLog(#"storeURL: %#", storeURL);
// NSPersistentStoreCoordinator *storeCoordinator = delegate.persistentStoreCoordinator;
// [storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
NSLog(#"There are errors: %#", error);
}
// delegate.persistentStoreCoordinator = nil;
// context = nil;
// delegate.managedObjectModel = nil;
}
The intention is you remove the lines of code that are commented out.

Automatic lightweight migration works for local storage but iCloud storage "loses" all legacy data

I'm tearing my hair out with this one.
I've got an App on iTunes which I added iCloud support to end of last year (Oct '13) on iOS7.0
This week I decided to write a new functional for the App which requires a new entity in the xcdatamodel. A very simple change/addition. Should have no impact on the current data set.
I create a new v2 xcdatamodel and set it to Current Model version, compile and run and it works fine if I've got iCloud switch off on my iPad. I see previous saved data.
Run it again with iCloud switch on and I get a blank table with no data.
No error messages, nothing.
Hoping someone can throw some light on what I've done wrong here:
- (NSManagedObjectModel *)managedObjectModel {
if (__managedObjectModel != nil) {
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"UserData" withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
NSError *error = nil;
BOOL success = NO;
if((__persistentStoreCoordinator != nil)) {
return __persistentStoreCoordinator;
}
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
NSPersistentStoreCoordinator *psc = __persistentStoreCoordinator;
NSString *iCloudEnabledAppID = #"C3FUPX46ZG~com~software~App";
NSString *dataFileName = #"UserData.sqlite";
NSString *iCloudDataDirectoryName = #"CoreData.nosync";
NSString *iCloudLogsDirectoryName = #"CoreDataLogs";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *localStore = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:dataFileName];
NSURL *iCloud = [fileManager URLForUbiquityContainerIdentifier:nil];
if (iCloud && ([UserDefaults getIsiCloudOn])) {
// This iCloud storage fails to migrate.
NSURL *iCloudLogsPath = [NSURL fileURLWithPath:[[iCloud path] stringByAppendingPathComponent:iCloudLogsDirectoryName]];
if([fileManager fileExistsAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]] == NO) {
NSError *fileSystemError;
[fileManager createDirectoryAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]
withIntermediateDirectories:YES
attributes:nil
error:&fileSystemError];
if(fileSystemError != nil) {
NSLog(#"Error creating database directory %#", fileSystemError);
}
}
NSString *iCloudData = [[[iCloud path]
stringByAppendingPathComponent:iCloudDataDirectoryName]
stringByAppendingPathComponent:dataFileName];
NSDictionary *options = #{NSMigratePersistentStoresAutomaticallyOption : #YES,
NSInferMappingModelAutomaticallyOption : #YES,
NSPersistentStoreUbiquitousContentNameKey : iCloudEnabledAppID,
NSPersistentStoreUbiquitousContentURLKey : iCloudLogsPath
};
success = [psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[NSURL fileURLWithPath:iCloudData]
options:options
error:&error];
if (!success) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
} else {
// This local storage migrates automatically just fine.
NSDictionary *options = #{NSMigratePersistentStoresAutomaticallyOption : #YES,
NSInferMappingModelAutomaticallyOption : #YES
};
success = [psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:localStore
options:options
error:&error];
if (!success) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:kCoreDataChangeNotification object:self userInfo:nil];
});
return __persistentStoreCoordinator;
}
UPDATE: Switched on core data debugging & iCloud debugging/logging.
Migration works for both local & iCloud. Logs are the same, ending with:
CoreData: annotation: (migration) inferring a mapping model between data models with...
CoreData: annotation: (migration) in-place migration completed succeessfully in 0.03 seconds
-PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:: CoreData: Ubiquity: mobile~F9AC6EB1
Using local storage: 1
With iCloud storage & debugging on it seems to cause a delay and I briefly see my saved data for about 10seconds when it then disappears.
Just before it disappears the debugs spit out:
CoreData: annotation: (migration) inferring a mapping model between data models with...
Using local storage: 0
The iCloud logs are enormous which is why I'm not posting them here. From what I can see I have over 400 log files and iCloud seems to be doing some sort of syncing. If I leave the App and iPad open and on for a few hours I still see an empty data set. So it's not a case of waiting for a sync catch up. I'm still at a loss even with the debugs on....

UIAlertView does not show up from the Appdelegate

I am working on core data migration. I am trying to handle exception when the persistent stores do not match and the app crashes. But before it crashes, i would like to let the user know (through an alert view) that he needs to uninstall the app first, and the re-install it. I have the code for the alert view in persistentStoreCoordinator accessor method, but the alertview never shows up.
Here is the code:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"ExchangeMail.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
// Dictionary required to store the details of psc on the disk,
NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:storeURL error:&error];
// This BOOL value is required to check whether a migration is required or not.
BOOL pscCompatibile = [[self managedObjectModel] isConfiguration:nil compatibleWithStoreMetadata:sourceMetadata];
NSLog(#"Migration needed? %d", !pscCompatibile);
NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setValue:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setValue:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Non-matching Database File" message:#"The model configuration used to open the store is compatible with the one that was used to create the store. Please Uninstall the App and try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[__persistentStoreCoordinator lock];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
// dispatch_queue_t queue = NULL;
// queue = dispatch_get_main_queue();
// dispatch_async(queue, ^{
// [[NSFileManager defaultManager]removeItemAtURL:storeURL error:nil];
//
// [self.myAlertView show];
// });
[self.myAlertView show];
//exit(-1);
}
[__persistentStoreCoordinator unlock];
if(!pscCompatibile){
isMigrationRequired = YES;
}
return __persistentStoreCoordinator;
}

Strange Core Data Error During Migration

I'm absolutely pulling my hair out with Core Data after yet another bizarre error that I can't seem to solve.
This will be the fourth version of the Data model, the previous migrations have worked (albeit with some headaches).
All I'm trying to do is add a property of String type to an 'Engines' entity. I create a new version of the model (version 4) based on the current version (v3). I select the newly created version 4 as the 'Current model' and add the string property to the Engines entity. I then create a new mapping model, using v3 as the source and v4 as the target. I delete the previous Engines NSManagedObject subclass, and create a new one using the new, modified Engines entity, checking to make sure that the new String property is in the header file. I clean build the app and run it, and boom! I get this error, about 18 times:
{NSDetailedErrors=(
"Error Domain=NSCocoaErrorDomain Code=1570 \"The operation couldn\U2019t be completed. (Cocoa error 1570.)\" UserInfo=0x6015820 {NSValidationErrorObject= (entity: BodySet; id: 0x60ba670 ; data: ), NSValidationErrorKey=availableCar, NSLocalizedDescription=The operation couldn\U2019t be completed. (Cocoa error 1570.)}",
BodySet is another entity in the model, but I haven't touched it during this migration, so why is it causing all these errors?
I'm not sure if this is a help or not, but here's my Core Data code:
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
NSString *path = [[NSBundle mainBundle] pathForResource:#"CoreDataTest" ofType:#"momd"];
NSURL *momURL = [NSURL fileURLWithPath:path];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];
return managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
stringByAppendingPathComponent:#"<Project Name>.sqlite"]];
//get the DB from the Documents directory:
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent: #"<Project Name>.sqlite"]];
NSLog(#"Loading DB at path: %#", [storeUrl path]);
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeUrl options:options error:&error]) {
/*Error for store creation should be handled in here*/
NSLog(#"Something went wrong....%#", [error description]);
}
return persistentStoreCoordinator;
}
Any help with this is very much appreciated.
i have fixed it ,maybe you can change "availableCar“ item to optional

Manual CoreData Migration with NSMigrationManager to append Data (preload)

I have a populated sqlite database in my app reousrce-folder. On startup I want to preload coredata-store with the data of this sqlite db. I use the NSMigrationManager in the persistantStoreCoordinator method. This works great at the first time and will append the data to the store. But it will append the data on each startup again, so the data will be duplicated, after the second startup. How can I solve this? In a database I would use primary keys, is there something similar in the data model? Or can I compare the entity-objects?
Thanks four your help, below the method I use:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:#"Raetselspass.sqlite"];
NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:#"Raetselspass" ofType:#"sqlite"];
NSURL *defaultStoreUrl = [NSURL fileURLWithPath:defaultStorePath];
/*
Set up the store.
For the sake of illustration, provide a pre-populated default store.
*/
// CANNOT USE THIS BELOW: WILL WORK ONCE, BUT WHEN I WILL UPDATE THE APP WITH
// NEW DATA TO APPEND, THEN THIS WILL NOT WORK
// NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn’t exist, copy the default store.
// if (![fileManager fileExistsAtPath:storePath]) {
// if (defaultStorePath) {
// [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
// }
// }
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
NSError *error;
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort(); // Fail
}
//migration
rror:&error];
NSError *err = nil;
NSMigrationManager *migrator = [[NSMigrationManager alloc] initWithSourceModel:[self managedObjectModel] destinationModel:[self managedObjectModel]];
NSMappingModel *mappingModel = [NSMappingModel inferredMappingModelForSourceModel:[self managedObjectModel] destinationModel:[self managedObjectModel] error:&err];
NSError *err2;
if (![migrator migrateStoreFromURL:defaultStoreUrl
type:NSSQLiteStoreType
options:nil
withMappingModel:mappingModel
toDestinationURL:storeUrl
destinationType:NSSQLiteStoreType
destinationOptions:nil
error:&err2])
{
//handle the error
}
NSLog(#"import finished");
[migrator release];
return persistentStoreCoordinator_;
}
The code as provided will merge the default file if it is present in the documents folder. If you delete the file after you merge it, then it shouldn't load every time. You could set a user default flag to record if it had been previously merged.
A better solution would be to create a Core Data persistent store with the default data and include that in the app bundle. Upon first launch, copy that file to the documents folder and just assign it to the persistent store. That method would be faster and you wouldn't have to worry about the merge failing.

Resources