Coredata and Cordova in ios 10 and 11 - ios

The belowe code works perfectly on native environment but if I use it in a Mobile first generated app it crashes. Moreover it only happens when I compile the project with iOS 10 SDK, up to iOS 9 SDK it works fine.
Message sent to deallocated instance Core Data iOS 10 Mobile First 7.1
I'm getting the following error every time I try to execute a request through NSManagedObjectContext.
*** -[_PFArray count]: message sent to deallocated instance 0x1c524f060
Here's the code:
NSError *error = nil;
NSArray *matches = [self processFetchRequest:fetchRequest error:&error];
if( matches.count > 0 ){
toReturn = (User*)[matches objectAtIndex:0];
}
where:
- (nullable NSArray*) processFetchRequest:(NSFetchRequest*)fetchRequest error:(NSError**)error{
__block NSArray *matches = nil;
#synchronized (self) {
NSManagedObjectContext *context = [self managedObjectContext];
[context performBlockAndWait:^{
matches = [context executeFetchRequest:fetchRequest error:error];
}];
}
return matches;
}
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = _managedObjectContext;
if ( context == nil ) {
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
}
return _managedObjectContext;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [self getStoreURL];
NSError *errorMetadata = nil;
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *storeOptions = #{NSPersistentStoreFileProtectionKey : NSFileProtectionCompleteUntilFirstUserAuthentication};
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:storeOptions
error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}

Related

Fatal Exception: NSInternalInconsistencyException Context already has a coordinator; cannot replace

In CoreData, while working with background and main context I am facing issue
Context already has a coordinator; cannot replace."
I am doing reading operation on the main context and writing operation on background context also for background context I am using background Queue. can you suggest what here i am doing wrong
========================================================================
Fatal Exception: NSInternalInconsistencyException
Context already has a coordinator; cannot replace.
#interface CoreDataCustomClass()
#property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, strong) NSManagedObjectContext *mainContext;
#property (nonatomic, strong) NSManagedObjectContext *backgroundContext;
#property (nonatomic, strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#end
static CoreDataCustomClass *sharedInstance = nil;
#implementation CoreDataCustomClass
+(CoreDataCustomClass *)sharedInstance
{
#synchronized([CoreDataCustomClass class])
{
if (!sharedInstance)
{
sharedInstance = [[self alloc] init];
}
return sharedInstance;
}
return nil;
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)mainContext {
if (_mainContext.persistentStoreCoordinator) {
return _mainContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__weak __typeof(self)weakSelf = self;
_mainContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_mainContext performBlockAndWait:^{
__strong __typeof(weakSelf)strongSelf = weakSelf;
[strongSelf->_mainContext setPersistentStoreCoordinator:coordinator];
}];
}
return _mainContext;
}
-(void)saveMainContext {
NSManagedObjectContext *mainManagedObjectContext = self.mainContext;
[mainManagedObjectContext performBlock:^{
NSError *error = nil;
if ([mainManagedObjectContext hasChanges] && ![mainManagedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
[mainManagedObjectContext performBlock:^{
NSError *error = nil;
if ([mainManagedObjectContext hasChanges] && ![mainManagedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
}];
}];
}
-(NSManagedObjectContext *)backgroundContext{
if (_backgroundContext.persistentStoreCoordinator){
return _backgroundContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if(coordinator != nil){
__weak __typeof(self)weakSelf = self;
_backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_backgroundContext performBlockAndWait:^{
__strong __typeof(weakSelf)strongSelf = weakSelf;
[strongSelf->_backgroundContext setPersistentStoreCoordinator:coordinator];
[strongSelf->_backgroundContext setUndoManager:nil];
}];
}
return _backgroundContext;
}
-(void)saveBackgroundContext {
NSManagedObjectContext *backgrounManagedObjectContext = self.backgroundContext;
[backgrounManagedObjectContext performBlock:^{
NSError *error = nil;
if ([backgrounManagedObjectContext hasChanges] && ![backgrounManagedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
[backgrounManagedObjectContext performBlock:^{
NSError *error = nil;
if ([backgrounManagedObjectContext hasChanges] && ![backgrounManagedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
}];
}];
}
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"abc" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSDictionary *persistentOptions = #{NSMigratePersistentStoresAutomaticallyOption:#YES, NSInferMappingModelAutomaticallyOption:#YES};
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"abc.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
[[NSFileManager defaultManager] removeItemAtURL: storeURL error: nil];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration: nil URL: storeURL options: nil error: &error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
}
NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey];
if (![[NSFileManager defaultManager] setAttributes:fileAttributes ofItemAtPath:[storeURL path] error:&error]) {
NSLog(#"error");
}
return _persistentStoreCoordinator;
}

nil is not a legal NSPersistentStoreCoordinator for searching for entity name 'GroupMessageInfo'

error message:
persistentStoreCoordinator is nil ??
persistentStoreCoordinator is nil ??
persistentStoreCoordinator is nil ??
persistentStoreCoordinator is nil ??
persistentStoreCoordinator is nil ??
persistentStoreCoordinator is nil ??
persistentStoreCoordinator is nil ??
persistentStoreCoordinator is nil ??
persistentStoreCoordinator is nil ??
------------ persistentStoreCoordinator is nil ??
- (void)updateGroupTableStatus:(TmpGroupMessageInfo*)info {
NSManagedObjectContext *ctx = [self createPrivateObjectContext];
[ctx performBlock:^{
NSPredicate *cdt = [NSPredicate predicateWithFormat:#"groupId == %# && tableId == %#", info.groupId, info.tableId];
NSFetchRequest *fetchRequest = [GroupMessageInfo makeRequest:ctx predicate:cdt orderby:nil offset:0 limit:1];
NSArray *array = [ctx executeFetchRequest:fetchRequest error:nil];
if ([array count] > 0) {
for (GroupMessageInfo *msg in array) {
msg.lastingTime = [NSNumber numberWithLongLong:0];
}
[ctx save:nil];
[self.managedObjectContext performBlock:^{
[self.managedObjectContext save:nil];
}];
}
}];
}
+ (NSFetchRequest*)makeRequest:(NSManagedObjectContext*)ctx predicate:(NSPredicate*)predicate orderby:(NSArray*)orders offset:(int)offset limit:(int)limit {
NSString *className = [NSString stringWithUTF8String:object_getClassName(self)];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:className inManagedObjectContext:ctx]];
if (predicate) {
[fetchRequest setPredicate:predicate];
}
if (orders!=nil) {
[fetchRequest setSortDescriptors:orders];
}
if (offset>0) {
[fetchRequest setFetchOffset:offset];
}
if (limit>0) {
[fetchRequest setFetchLimit:limit];
}
return fetchRequest;}
- (NSManagedObjectContext*)createPrivateObjectContext {
if (_privateManagedObjectContext == nil) {
_privateManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_privateManagedObjectContext setParentContext:self.managedObjectContext];
}
return _privateManagedObjectContext;
}
- (NSManagedObjectContext *)managedObjectContext {
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"PokerSkyModel" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
......
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:optionsDictionary error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
[self cleanData];
abort();
}
return _persistentStoreCoordinator;
}
I came a cross exactly the same crash with yours. Finally I found out that initialize persistentStoreCoordinator of NSManagedObjectContext cannot be placed in background thread!
In your case, you do some CoreData operation at No.11 thread which is obviously not the Main Thread.If it is the first time you access your CoreData, then the persistentStoreCoordinator will be set at your No.11 background thread which lead to the crash. You can also reproduce the crash by putting these code appDidFinishLaunch at AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// your CoreData operation here
}
// ...
}
The solution is quite easy, just ensure the initialization of CoreData(or the first time you use it) should be at Main Thread.When it's not, using GCD to switch to it
dispatch_async(dispatch_get_main_queue(), 0), ^{
// your CoreData initialize here
}

iOS 8 CoreData Issue: recordChangeSnapshot:forObjectID:: global ID may not be temporary when recording

I'm migrating my App from iOS 7 to iOS 8, and I've been receiving the following error in Xcode when I try to save the Core Data context. This error was not present in iOS 7 and Xcode 5. it throws exception at below line
NSError * saveError = nil;
if(![self.managedObjectContext save:&saveError])
{ // crash on save context line.
//error message.
}
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'recordChangeSnapshot:forObjectID:: global ID may not be temporary when recording.
I am sinking data on main thread and trying to save it in core data .
Below is code for managed object context in app delegate class :
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"MCRM" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"MCRM.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
and it crash in data manager class :
NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
Code work fine in iOS7 and Xcode5.1 .
I have already tried with thread confinement (-[NSManagedObjectContext init]) to replace with [NSManagedObjectContext initWithConcurrencyType:] to NSConfinementConcurrencyType and NSMainQueueConcurrencyType with performBlockWithWait^{} code injection but still facing issue .

Ios core data not saved

I'm using core data and i have a problem. When i save the data and the app is still running i can see and get the data that was saved.
Once the application is close, all the fields deleted and just the object is saved. I can see that in the saveContext method.
On first launch when the app is closing the saveContext method is activated. I can see that the managedObjectContext object is inserting new object.
The next times that the app is opening , the managedObjectContext is updating the object so i know it save the objects but when i try to retrive the object it can find .
here is how i insert objects:
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
self.managedObjectContext = appDelegate.managedObjectContext;
#try {
UserData *userData =[NSEntityDescription insertNewObjectForEntityForName:[UserTable tableName] inManagedObjectContext:self.managedObjectContext];
//Insert Values
userData.facebookId=user.id;
userData.name=user.name;
userData.picoAccessToken=[PicoApiManager sharedInstance].accessToken;
userData.picoExpire=[PicoApiManager sharedInstance].expires;
userData.latitude=[NSNumber numberWithDouble:user.latitude];
userData.longitude=[NSNumber numberWithDouble:user.longitude];
userData.pushId=user.pushId;
userData.isActive=[NSNumber numberWithBool:activeStatus];
}
#catch (NSException *exception) {
NSLog(#"Insert exception - %#", exception.description);
}
or
-(void)addPictures:(NSMutableArray *)Pictures;
{
//Setting the isNew field to NO to all the pictures already in the db
[self updateIsNewOfPicture];
for (Picture *picture in Pictures) {
//Checks if inserted picture is already inside the table
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
self.managedObjectContext = appDelegate.managedObjectContext;
#try {
PictureData *pictureData=[NSEntityDescription insertNewObjectForEntityForName:[PicturesTable tableName]inManagedObjectContext:self.managedObjectContext];
//Insert Values
pictureData.url=picture.source;
pictureData.isNew=[NSNumber numberWithBool:YES];
pictureData.isPick=[NSNumber numberWithBool:NO];
pictureData.timeTaken=picture.time_taken;
pictureData.albumData=[self getActiveAlbum];
}
#catch (NSException *exception) {
NSLog(#"Insert exception - %#", exception.description);
}
}
This is app delegate functions:
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
}
}
#pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Pico-Db" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Pico.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
This is how i'm trying to get the data :
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
//2
// initializing NSFetchRequest
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//Setting Entity to be Queried
NSEntityDescription *entity = [NSEntityDescription entityForName:[UserTable tableName] inManagedObjectContext:appDelegate.managedObjectContext];
[fetchRequest setEntity:entity];
NSError* error;
// Query on managedObjectContext With Generated fetchRequest
NSArray *fetchedRecords = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedRecords.count >0) {
return YES;
}
return NO;
You must call -[AppDelegate saveContext] after inserting your data in order for CoreData to persist changes to disk. The NSManagedObjectContext will store changes in memory so while your application is still active, you will have access to the data. As soon as the app terminates, however, unless you call -[AppDelegate saveContext] those changes will not be persisted.
Try this in the first example:
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
self.managedObjectContext = appDelegate.managedObjectContext;
#try {
UserData *userData = [NSEntityDescription insertNewObjectForEntityForName:[UserTable tableName] inManagedObjectContext:self.managedObjectContext];
//Insert Values
userData.facebookId=user.id;
userData.name=user.name;
userData.picoAccessToken=[PicoApiManager sharedInstance].accessToken;
userData.picoExpire=[PicoApiManager sharedInstance].expires;
userData.latitude=[NSNumber numberWithDouble:user.latitude];
userData.longitude=[NSNumber numberWithDouble:user.longitude];
userData.pushId=user.pushId;
userData.isActive=[NSNumber numberWithBool:activeStatus];
} #catch (NSException *exception) {
NSLog(#"Insert exception - %#", exception.description);
}
// SAVE CONTEXT:
[appDelegate saveContext];
Try this in the second example:
for (Picture *picture in Pictures) {
// Checks if inserted picture is already inside the table
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
self.managedObjectContext = appDelegate.managedObjectContext;
#try {
PictureData *pictureData = [NSEntityDescription insertNewObjectForEntityForName:[PicturesTable tableName]inManagedObjectContext:self.managedObjectContext];
//Insert Values
pictureData.url=picture.source;
pictureData.isNew=[NSNumber numberWithBool:YES];
pictureData.isPick=[NSNumber numberWithBool:NO];
pictureData.timeTaken=picture.time_taken;
pictureData.albumData=[self getActiveAlbum];
} #catch (NSException *exception) {
NSLog(#"Insert exception - %#", exception.description);
}
}
// SAVE CONTEXT:
[appDelegate saveContext];
To create a fetch request:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"YourEntityName"];
request.sortDescriptors = [NSSortDescriptor sortDescriptorWithKey:#"attributeName" ascending:YES];
request.predicate = [NSPredicate predicateWithFormat:#"attribute == %#", 13];
NSError *error = nil; //
NSArray *results = [appDelegate.managedObjectContext executeFetchRequest:request error:&error];
if (!results) {
NSLog(#"Error performing fetch request: %#", error.localizedDescription);
}
return ([results count] > 0); // There are more efficient ways of getting count from CoreData

Error while saving object in coredata

Here is my code:
- (IBAction) saveData
{
NSLog(#"saveData");
[self dismissKeyboard];
Fugitive *job = (Fugitive *)[NSEntityDescription insertNewObjectForEntityForName:#"Fugitive" inManagedObjectContext:managedObjectContext];
job.name = txtName.text;
NSError *error;
// here's where the actual save happens, and if it doesn't we print something out to the console
if (![managedObjectContext save:&error])
{
NSLog(#"Problem saving: %#", [error localizedDescription]);
}
// **** log objects currently in database ****
// create fetch object, this object fetch's the objects out of the database
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Fugitive" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSURL *storeURL = [[NSBundle mainBundle] URLForResource:#"iBountyHunter" withExtension:#"momd"];
id globalStore = [[managedObjectContext persistentStoreCoordinator] persistentStoreForURL:storeURL];
[managedObjectContext assignObject:job toPersistentStore:globalStore];
for (NSManagedObject *info in fetchedObjects)
{
NSLog(#"Job Name: %#", [info valueForKey:#"name"]);
}
[fetchRequest release];
[self.navigationController dismissModalViewControllerAnimated:YES];
}
In the console I get this error: Problem saving: The operation couldn’t be completed. (Cocoa error 1570.)
The new object is created in the tableview, but not saved thus when re-launching the app, the object disappears
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
- (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;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"iBountyHunter" withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"iBountyHunter.sqlite"];
NSError *error = nil;
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}

Resources