Core Data fetching deleted objects - ios

Short version of my problem: I'm deleting an object and after I do a fetch that returns the previously deleted object.
I'm following this architecture:
SyncService -> Persistence Service -> NSManagedObject
All my classes in Persistence Service layer are children of the following class:
# PersistenceService.h
#import <Foundation/Foundation.h>
#interface PersistenceService : NSObject
#property (nonatomic, retain) NSManagedObjectContext *context;
-(instancetype) init;
-(void) saveContext;
#end
# PersistenceService.m
#implementation PersistenceService
-(instancetype) init {
self = [super init];
if (self) {
self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
self.context.parentContext = [DataManager sharedInstance].managedObjectContext;
}
return self;
}
-(void) saveContext {
NSManagedObjectContext *context = self.context.parentContext;
[self.context performBlock:^{
NSError *error;
[self.context save:&error];
[context performBlock:^{
NSError *error;
[context save:&error];
[context.parentContext performBlock:^{
NSError *error;
[context.parentContext save:&error];
}];
}];
}];
}
#end
Before the deletion, I fetch the object in my main context:
# Synchronizer.m
-(void) synchronize {
NSArray *pseudoLeads = [[[PseudoLeadPersistenceService alloc] init] getAllParentPseudoLeads];
if (pseudoLeads) {
PseudoLeadDAO *pseudoLead = [pseudoLeads objectAtIndex:0];
if ([pseudoLead.type isEqualToNumber:[NSNumber numberWithInt:Capture]]) {
CaptureSyncService *service = [[CaptureSyncService alloc] initWithDelegate:self andPseudoLead:pseudoLead];
[service executeRequest];
} else {
HotleadSyncService *service = [[HotleadSyncService alloc] initWithDelegate:self andPseudoLead:pseudoLead];
[service executeRequest];
}
}
}
.
# PseudoLeadPersistenceService.m
-(NSArray *) getAllParentPseudoLeads {
return [PseudoLeadDAO findAllParentPseudoLeadsInContext:self.context.parentContext];
}
And here I fetch and actually delete the object in my subcontext:
# PseudoLeadPersistenceService.m
-(void) deletePseudoLeadById:(NSNumber *)pseudoLeadId andEventId:(NSNumber *)eventId {
PseudoLeadDAO *pseudoLeadDAO = [PseudoLeadDAO findPseudoLeadById:pseudoLeadId andEventId:eventId inContext:self.context];
[self.context deleteObject:pseudoLeadDAO];
[self saveContext];
}
Then the -(void) synchronize is called again and the deleted object shows up again as a fault. At this point, I can fetch as many times as I want and it will be returned. It only goes away when it comes to -(void) deletePseudoLeadById:(NSNumber *)pseudoLeadId andEventId:(NSNumber *)eventId method again and the fault is fired.
I'll appreciate any help given. Thanks!

The problem was concurrency. The thread started to save the context wasn't getting done before the next fetch.
I solved the problem by using performBlockAndWait:
# PersistenceService.m
-(void) saveContextAndWait {
NSManagedObjectContext *context = self.context.parentContext;
[self.context performBlockAndWait:^{
NSError *error;
[self.context save:&error];
[context performBlockAndWait:^{
NSError *error;
[context save:&error];
[context.parentContext performBlockAndWait:^{
NSError *error;
[context.parentContext save:&error];
}];
}];
}];
}
.
# PseudoLeadPersistenceService.m
-(void) deletePseudoLeadById:(NSNumber *)pseudoLeadId andEventId:(NSNumber *)eventId {
PseudoLeadDAO *pseudoLeadDAO = [PseudoLeadDAO findPseudoLeadById:pseudoLeadId andEventId:eventId inContext:self.context];
[self.context deleteObject:pseudoLeadDAO];
[self saveContextAndWait];
}

Related

Error and Crash when using the Core Data to create a UITableView

I try to use Core Data to make a UITableView, but I come across a crash when I run it:
014-07-29 10:13:12.443 TableAndCoreData[797:60b] -[AppDelegate managedObjectContext]: unrecognized selector sent to instance 0x8f319a0
2014-07-29 10:13:12.446 TableAndCoreData[797:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppDelegate managedObjectContext]: unrecognized selector sent to instance 0x8f319a0'
I generally check it and I guess it might be the problem of the creating the managedObjectContext. Does any one have some idea to help me to fix this problem?
#interface DetailViewController ()
#property (weak, nonatomic) IBOutlet UITextField *nameTextField;
#property (weak, nonatomic) IBOutlet UITextField *ageTextField;
#end
#implementation DetailViewController
// Set NSManagedObjectContext
- (NSManagedObjectContext *) managedOjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication]delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedOjectContext];
}
return context;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)cancelButton:(UIButton *)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)saveButton:(UIButton *)sender
{
[self save];
}
- (void)save
{
// Get ManagedObjectContext
NSManagedObjectContext *context = [self managedOjectContext];
// Create a ManagedObject
NSManagedObject *aPerson = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:context];
// Set value for the attributes of the entity
[aPerson setValue:self.nameTextField.text forKey:#"name"];
[aPerson setValue:self.ageTextField.text forKey:#"age"];
// Check the error
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't save due to %#%#", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
Besides, I am trying another way to create UITableView using Core Data:
- (void) save
{
// Create UIManagedDocument
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentDirectory = [[fileManager URLsForDirectory:NSDocumentationDirectory inDomains:NSUserDomainMask]firstObject];
NSString *documentName = #"Model";
NSURL *url = [documentDirectory URLByAppendingPathComponent:documentName];
UIManagedDocument *document = [[UIManagedDocument alloc]initWithFileURL:url];
if ([fileManager fileExistsAtPath:[url path]]) {
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
if (document.documentState == UIDocumentStateNormal) {
// Get a ManagedObjectContext
NSManagedObjectContext *context = document.managedObjectContext;
// Set managed object (entity)
NSManagedObject *aPerson = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:context];
// Set value for the attribute (which are "name" and "age") of the entity
[aPerson setValue:self.nameTextField.text forKey:#"name"];
[aPerson setValue:self.ageTextField.text forKey:#"age"];
// Check whether there is an error
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't save due to %#%#", error, [error localizedDescription]);
}
// Close the window
[self dismissViewControllerAnimated:YES completion:nil];
}
}
if (!success) {
NSLog(#"couldn't open document at %#", url);
}
}];
}
else {
[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
if (document.documentState == UIDocumentStateNormal) {
// Get a ManagedObjectContext
NSManagedObjectContext *context = document.managedObjectContext;
// Set managed object (entity)
NSManagedObject *aPerson = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:context];
// Set value for the attribute (which are "name" and "age") of the entity
[aPerson setValue:self.nameTextField.text forKey:#"name"];
[aPerson setValue:self.ageTextField.text forKey:#"age"];
// Check whether there is an error
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't save due to %#%#", error, [error localizedDescription]);
}
// Close the window
[self dismissViewControllerAnimated:YES completion:nil];
}
}
if (!success) {
NSLog(#"couldn't open document at %#", url);
}
}];
}
}
However, it just couldn't find the UIManagedDocument. I really wonder the reason why I should create a UIManagedDocument and the document name I should name it.
Your crash does not have anything to do with Core Data.
Change this:
[delegate performSelector:#selector(managedObjectContext)]
to:
[delegate respondsToSelector:#selector(managedObjectContext)]
The crash was happening because you were sending the message managedObjectContext to the application delegate object, which does not respond to that message. It was being sent because where you meant to check to see if it responds to that message with respondsToSelector:, you had performSelector instead. Your application delegate object still needs to implement managedObjectContext for your code to be functional, but the portions you have posted should no longer crash as you describe.
In general you want to avoid calling a method on the application delegate this way. It's preferred to pass a value like this from the application delegate into the root view controller at startup, and it's passed along to the next view controller and the next.
There is a slightly outdated, but still relevant section of the Core Data documentation that discusses this:
A view controller typically shouldn’t retrieve the context from a global object such as the application delegate—this makes the application architecture rigid. Neither should a view controller create a context for its own use (unless it’s a nested context).
...as well as the iOS 5 release notes:
Nested contexts make it more important than ever that you adopt the “pass the baton” approach of accessing a context (by passing a context from one view controller to the next) rather than retrieving it directly from the application delegate.

core data: background context ios

I already posted this problem and no one tell me what is the problem, please help.
I have problem when I use Core Data to save data in my iOS app.
My application can receive many and many text message in a second from a server.
So i need to save those message in my data base, now i use NSOperations inside queue to save messages (so you can imagine the number of the NSOperation in the NSOperationQueue).
The problem is if the i have a normal flow of messages then it works fine and if have an important flow of messages , the app freeze indefinitely or the NSOperations increase without limit in the queue.
PS: if remove the observer of merge the messages are saved without any problem
This my code of the NSOperation:
#interface SaveRecievedMessageOperation()
#property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, strong) AppDelegate *appdelegate;
#property (nonatomic, assign) BOOL executing;
#property (nonatomic, assign) BOOL finished;
#end
#implementation SaveRecievedMessageOperation
#synthesize message;
#synthesize managedObjectContext;
#synthesize appdelegate;
#synthesize executing;
#synthesize finished;
- (id)initWithMessage:(SipMessage *)messageToSave
{
if (self = [super init]) {
self.message = messageToSave;
}
return self;
}
- (void)main
{
#autoreleasepool
{
self.appdelegate = [[UIApplication sharedApplication] delegate];
[self managedObjectContext];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:self.managedObjectContext];
[self saveMessage];
}
}
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil)
{
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self.appdelegate persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
[managedObjectContext setMergePolicy:NSOverwriteMergePolicy];
}
return managedObjectContext;
}
- (void)saveMessage
{
NSDictionary *header = self.message.headers;
NSArray *bodies = self.message.bodies;
SipBody *sipBody;
NSDictionary* body;
NSData *ContentData;
if ([[header valueForKey:#"Content-Type"] rangeOfString:#"application/json"].location != NSNotFound)
{
sipBody = [bodies objectAtIndex:0];
body = [NSJSONSerialization
JSONObjectWithData:sipBody.content
options:NSJSONReadingAllowFragments
error:nil];
}
else if ([[header valueForKey:#"Content-Type"] rangeOfString:#"multipart/mixed"].location != NSNotFound)
{
for (SipBody *sipB in bodies) {
if ([[sipB.headers valueForKey:#"Content-Type"] rangeOfString:#"application/json"].location != NSNotFound)
{
body = [NSJSONSerialization
JSONObjectWithData:sipB.content
options:NSJSONReadingAllowFragments
error:nil];
}
else
{
ContentData = [NSData dataWithData:sipB.content];
}
}
}
else
{
return;
}
MGMPhone *sender;
NSArray *senders = [self updatePhonesFromMSISDNsList:[[header valueForKey:#"swfrom"] componentsSeparatedByString:MGMseparator]];
sender = senders[0];
NSError *error;
MGMMessage *aMesage = [MGMMessage createInContext:self.managedObjectContext];
[aMesage setBoxType:[NSNumber numberWithInteger:BoxTypeIncomingMessage]];
[aMesage setContent:[body valueForKey:#"Content"]];
[aMesage setContentType:[header valueForKey:#"Content-Type"]];
[aMesage setGroupMessage:( [[header valueForKey:#"groupmessage"] isEqualToString:#"true"]
?
[self saveContext];
}
#pragma mark core data
- (void)mergeChanges:(NSNotification *)notification
{
dispatch_async(dispatch_get_main_queue(), ^{
NSManagedObjectContext *mainContext = [appdelegate managedObjectContext];
[mainContext performSelector:#selector(mergeChangesFromContextDidSaveNotification:) withObject:notification];
[self setManagedObjectContext:nil];
}
- (void)saveContext
{
NSError *error = nil;
if (self.managedObjectContext != nil)
{
if ([self.managedObjectContext hasChanges]) {
BOOL isSaved = [self.managedObjectContext save:&error];
if(!isSaved){
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
else if (![self.managedObjectContext hasChanges]){
[self setManagedObjectContext:nil];
}
}
}
#end
I think everything is fine, except the merge operation. I'm using very similar CoreData operations in background myself.
Typically you want to merge updates from background operations with the 'main' managed object context. So basically in the background operation you should only perform the save: method. (So don't register for save notifications nor initiate merge actions).
Unless you really need to merge managed object contexts in background threads, the save notification should be registered only once in the main thread (typically in a singleton e.g. appDelegate or your own singleton). The save notification will be sent by CoreData after any save operation in other contexts, allowing you to merge these changes with the main context.

CoreData saving on GCD background queue hangup on iPad Mini

I have a singleton class that saves JSON objects to a CoreData database in the background using GCD (Grand Central Dispatch) queues. This works perfectly the majority of the time, but on iPad 2 and iPad Mini devices I am experiencing some issues with the process freezing.
My setup is pretty straight forward. I have a background dispatch queue (backgroundQueue) that is set to run serially, and I have a seperate instance of NSManagedObjectContext for the background queue. When I want to save something to the database I call the method that begins the save process, and In that method I use dispatch_async to invoke my save logic on the background thread.
Once all processing logic has ran I save the background MOC, and use NSManagedObjectContextDidSaveNotification to merge the changes from the background MOC to the main thread MOC. The background thread waits for this to complete, and once it's done it'll run the next block in the queue, if any. Below is my code.
dispatch_queue_t backgroundQueue;
- (id)init
{
if (self = [super init])
{
// init the background queue
backgroundQueue = dispatch_queue_create(VS_CORE_DATA_MANAGER_BACKGROUND_QUEUE_NAME, DISPATCH_QUEUE_SERIAL);
}
return self;
}
- (void)saveJsonObjects:(NSDictionary *)jsonDict
objectMapping:(VS_ObjectMapping *)objectMapping
class:(__unsafe_unretained Class)managedObjectClass
completion:(void (^)(NSArray *objects, NSError *error))completion
{
[VS_Log logDebug:#"**** Queue Save JSON Objects for Class: %#", managedObjectClass];
// process in the background queue
dispatch_async(backgroundQueue, ^(void)
{
[VS_Log logDebug:#"**** Dispatch Save JSON Objects for Class: %#", managedObjectClass];
// create a new process object and add it to the dictionary
currentRequest = [[VS_CoreDataRequest alloc] init];
// set the thead name
NSThread *currentThread = [NSThread currentThread];
[currentThread setName:VS_CORE_DATA_MANAGER_BACKGROUND_THREAD_NAME];
// if there is not already a background context, then create one
if (!_backgroundQueueManagedObjectContext)
{
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
// create the background queue
_backgroundQueueManagedObjectContext = [[NSManagedObjectContext alloc] init];
[_backgroundQueueManagedObjectContext setPersistentStoreCoordinator:coordinator];
[_backgroundQueueManagedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
_backgroundQueueManagedObjectContext.undoManager = nil;
// listen for the merge changes from context did save notification on the background queue
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(mergeChangesFromBackground:) name:NSManagedObjectContextDidSaveNotification object:_backgroundQueueManagedObjectContext];
}
}
// save the JSON dictionary
NSArray *objects = [self saveJSON:jsonDict objectMapping:objectMapping class:managedObjectClass managedObjectContext:_backgroundQueueManagedObjectContext level:0];
// save the objects so we can access them later to be re-fetched and returned on the main thread
if (objects.count > 0)
[currentRequest.objects addObjectsFromArray:objects];
// save the object IDs and the completion block to global variables so we can access them after the save
if (completion)
currentRequest.completionBlock = completion;
[VS_Log logDebug:#"**** Save MOC for Class: %#", managedObjectClass];
// save all changes object context
[self saveManagedObjectContext];
});
}
- (void)mergeChangesFromBackground:(NSNotification *)notification
{
[VS_Log logDebug:#"**** Merge Changes From Background"];
// save the current request to a local var since we're about to be processing it on the main thread
__block VS_CoreDataRequest *request = (VS_CoreDataRequest *)[currentRequest copy];
__block NSNotification *bNotification = (NSNotification *)[notification copy];
// clear out the request
currentRequest = nil;
dispatch_sync(dispatch_get_main_queue(), ^(void)
{
[VS_Log logDebug:#"**** Start Merge Changes On Main Thread"];
// merge changes to the primary context, and wait for the action to complete on the main thread
[_managedObjectContext mergeChangesFromContextDidSaveNotification:bNotification];
NSMutableArray *objects = [[NSMutableArray alloc] init];
// iterate through the updated objects and find them in the main thread MOC
for (NSManagedObject *object in request.objects)
{
NSError *error;
NSManagedObject *obj = [[self managedObjectContext] existingObjectWithID:object.objectID error:&error];
if (error)
[self logError:error];
if (obj)
[objects addObject:obj];
}
// call the completion block
if (request.completionBlock)
{
void (^saveCompletionBlock)(NSArray *, NSError *) = request.completionBlock;
saveCompletionBlock(objects, nil);
}
[VS_Log logDebug:#"**** Complete Merge Changes On Main Thread"];
// clear the request
request = nil;
});
[VS_Log logDebug:#"**** Complete Merge Changes From Background"];
}
When the issue occurs everything seems to run fine, and it gets into the mergeChangesFromBackground: method, but the dispatch_async() is not invoked.
As I mentioned above the code runs perfectly in most cases. Only time it has issues running is when I am testing on either an iPad 2 or iPad Mini and saving large objects.
Does anyone out there have any ideas why this is happening?
Thanks
** EDIT **
Since writing this I've learned of nested NSManagedObjectContexts. I have modified my code to use it and it seems to be working well. However, I still have the same issues. Thoughts? Also, any comments on nested MOCs?
- (void)saveJsonObjects:(NSDictionary *)jsonDict
objectMapping:(VS_ObjectMapping *)objectMapping
class:(__unsafe_unretained Class)managedObjectClass
completion:(void (^)(NSArray *objects, NSError *error))completion
{
// process in the background queue
dispatch_async(backgroundQueue, ^(void)
{
// create a new process object and add it to the dictionary
__block VS_CoreDataRequest *currentRequest = [[VS_CoreDataRequest alloc] init];
// set the thead name
NSThread *currentThread = [NSThread currentThread];
[currentThread setName:VS_CORE_DATA_MANAGER_BACKGROUND_THREAD_NAME];
// if there is not already a background context, then create one
if (!_backgroundQueueManagedObjectContext)
{
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
// create the background queue
_backgroundQueueManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_backgroundQueueManagedObjectContext setParentContext:[self managedObjectContext]];
[_backgroundQueueManagedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
_backgroundQueueManagedObjectContext.undoManager = nil;
}
}
// save the JSON dictionary starting at the upper most level of the key path
NSArray *objects = [self saveJSON:jsonDict objectMapping:objectMapping class:managedObjectClass managedObjectContext:_backgroundQueueManagedObjectContext level:0];
// if no objects were processed, then return with an error
if (!objects || objects.count == 0)
{
currentRequest = nil;
// dispatch the completion block
dispatch_async(dispatch_get_main_queue(), ^(void)
{
NSError *error = [self createErrorWithErrorCode:100 description:#"No objects were found for the object mapping"];
[self logMessage:error.debugDescription];
completion(nil, error);
});
}
// save the objects so we can access them later to be re-fetched and returned on the main thread
if (objects.count > 0)
[currentRequest.objects addObjectsFromArray:objects];
// save the object IDs and the completion block to global variables so we can access them after the save
if (completion)
currentRequest.completionBlock = completion;
// save all changes object context
NSError *error = nil;
[_backgroundQueueManagedObjectContext save:&error];
if (error)
[VS_Log logError:error.localizedDescription];
dispatch_sync(dispatch_get_main_queue(), ^(void)
{
NSMutableArray *objects = [[NSMutableArray alloc] init];
// iterate through the updated objects and find them in the main thread MOC
for (NSManagedObject *object in currentRequest.objects)
{
NSError *error;
NSManagedObject *obj = [[self managedObjectContext] existingObjectWithID:object.objectID error:&error];
if (error)
[self logError:error];
if (obj)
[objects addObject:obj];
}
// call the completion block
if (currentRequest.completionBlock)
{
void (^saveCompletionBlock)(NSArray *, NSError *) = currentRequest.completionBlock;
saveCompletionBlock(objects, nil);
}
});
// clear out the request
currentRequest = nil;
});
}
** EDIT **
Hi Everyone,
I'd first like to thank everyone for this input on this, as that is what lead me to finding the solution for my problem. Long story short I did away completely with using the GCD and the custom background queue, and instead am now using nested contexts and the "performBlock" method to perform all saving on the background thread. This is working great and I elevated my hang up issue.
However, I now have a new bug. Whenever I run my app for the first time, whenever I try to save an object that has child object relations, I get the following exception.
-_referenceData64 only defined for abstract class. Define -[NSTemporaryObjectID_default _referenceData64]!
Below is my new code.
- (void)saveJsonObjects:(NSDictionary *)jsonDict
objectMapping:(VS_ObjectMapping *)objectMapping
class:(__unsafe_unretained Class)managedObjectClass
completion:(void (^)(NSArray *objects, NSError *error))completion
{
[_backgroundManagedObjectContext performBlock:^(void)
{
// create a new process object and add it to the dictionary
VS_CoreDataRequest *currentRequest = [[VS_CoreDataRequest alloc] init];
currentRequest.managedObjectClass = managedObjectClass;
// save the JSON dictionary starting at the upper most level of the key path
NSArray *objects = [self saveJSON:jsonDict objectMapping:objectMapping class:managedObjectClass managedObjectContext:_backgroundManagedObjectContext level:0];
if (objects.count == 0)
{
currentRequest.error = [self createErrorWithErrorCode:100 description:#"No objects were found for the object mapping"];
[self performSelectorOnMainThread:#selector(backgroundSaveProcessDidFail:) withObject:currentRequest waitUntilDone:NO];
}
else
{
// save the objects so we can access them later to be re-fetched and returned on the main thread
[currentRequest.objects addObjectsFromArray:objects];
// save the object IDs and the completion block to global variables so we can access them after the save
currentRequest.completionBlock = completion;
[_backgroundManagedObjectContext lock];
#try
{
[_backgroundManagedObjectContext processPendingChanges];
[_backgroundManagedObjectContext save:nil];
}
#catch (NSException *exception)
{
currentRequest.error = [self createErrorWithErrorCode:100 description:exception.reason];
}
[_backgroundManagedObjectContext unlock];
// complete the process on the main thread
if (currentRequest.error)
[self performSelectorOnMainThread:#selector(backgroundSaveProcessDidFail:) withObject:currentRequest waitUntilDone:NO];
else
[self performSelectorOnMainThread:#selector(backgroundSaveProcessDidSucceed:) withObject:currentRequest waitUntilDone:NO];
// clear out the request
currentRequest = nil;
}
}];
}
- (void)backgroundSaveProcessDidFail:(VS_CoreDataRequest *)request
{
if (request.error)
[self logError:request.error];
if (request.completionBlock)
{
void (^saveCompletionBlock)(NSArray *, NSError *) = request.completionBlock;
saveCompletionBlock(nil, request.error);
}
}
- (void)backgroundSaveProcessDidSucceed:(VS_CoreDataRequest *)request
{
// get objects from main thread
NSArray *objects = nil;
if (request.objects.count > 0)
{
NSFetchRequest *fetchReq = [NSFetchRequest fetchRequestWithEntityName:[NSString stringWithFormat:#"%#", request.managedObjectClass]];
fetchReq.predicate = [NSPredicate predicateWithFormat:#"self IN %#", request.objects];
objects = [self executeFetchRequest:fetchReq];
}
// call the completion block
if (request.completionBlock)
{
void (^saveCompletionBlock)(NSArray *, NSError *) = request.completionBlock;
saveCompletionBlock(objects, nil);
}
}
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
// create the MOC for the backgroumd thread
_backgroundManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_backgroundManagedObjectContext setPersistentStoreCoordinator:coordinator];
[_backgroundManagedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
_backgroundManagedObjectContext.undoManager = nil;
// create the MOC for the main thread
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setParentContext:_backgroundManagedObjectContext];
[_managedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
}
return _managedObjectContext;
}
Do any of you have any idea why this crash is happening?
You might want to consider this kind of context architecture (untested code):
The mainManagedObjectContext will be initialised in the same manner but with NSMainQueueConcurrencyType and no observer (by the way, remember to remove your observer)
- (void) mergeChangesFromBackground:(NSNotification*)notification
{
__block __weak NSManagedObjectContext* context = self.managedObjectContext;
[context performBlockAndWait:^{
[context mergeChangesFromContextDidSaveNotification:notification];
}];
}
- (NSManagedObjectContext*) bgContext
{
if (_bgContext) {
return _bgContext;
}
NSPersistentStoreCoordinator* coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_bgContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_bgContext setPersistentStoreCoordinator:coordinator];
[_bgContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
[_bgContext setUndoManager:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(mergeChangesFromBackground:)
name:NSManagedObjectContextDidSaveNotification
object:_bgContext];
return _bgContext;
}
- (void) doSomethingOnBGContextWithoutBlocking:(void(^)(NSManagedObjectContext*))contextBlock
{
__block __weak NSManagedObjectContext* context = [self bgContext];
[context performBlock:^{
NSThread *currentThread = [NSThread currentThread];
NSString* prevName = [currentThread name];
[currentThread setName:#"BGContextThread"];
contextBlock(context);
[context reset];
[currentThread setName:prevName];
}];
}
I'd first like to thank everyone for this input on this, as that is what lead me to finding the solution for my problem. Long story short I did away completely with using the GCD and the custom background queue, and instead am now using nested contexts and the "performBlock" method to perform all saving on the background thread. This is working great and I elevated my hang up issue.
However, I now have a new bug. Whenever I run my app for the first time, whenever I try to save an object that has child object relations, I get the following exception.
-_referenceData64 only defined for abstract class. Define -[NSTemporaryObjectID_default _referenceData64]!
Below is my new code.
- (void)saveJsonObjects:(NSDictionary *)jsonDict
objectMapping:(VS_ObjectMapping *)objectMapping
class:(__unsafe_unretained Class)managedObjectClass
completion:(void (^)(NSArray *objects, NSError *error))completion
{
[_backgroundManagedObjectContext performBlock:^(void)
{
// create a new process object and add it to the dictionary
VS_CoreDataRequest *currentRequest = [[VS_CoreDataRequest alloc] init];
currentRequest.managedObjectClass = managedObjectClass;
// save the JSON dictionary starting at the upper most level of the key path
NSArray *objects = [self saveJSON:jsonDict objectMapping:objectMapping class:managedObjectClass managedObjectContext:_backgroundManagedObjectContext level:0];
if (objects.count == 0)
{
currentRequest.error = [self createErrorWithErrorCode:100 description:#"No objects were found for the object mapping"];
[self performSelectorOnMainThread:#selector(backgroundSaveProcessDidFail:) withObject:currentRequest waitUntilDone:NO];
}
else
{
// save the objects so we can access them later to be re-fetched and returned on the main thread
[currentRequest.objects addObjectsFromArray:objects];
// save the object IDs and the completion block to global variables so we can access them after the save
currentRequest.completionBlock = completion;
[_backgroundManagedObjectContext lock];
#try
{
[_backgroundManagedObjectContext processPendingChanges];
[_backgroundManagedObjectContext save:nil];
}
#catch (NSException *exception)
{
currentRequest.error = [self createErrorWithErrorCode:100 description:exception.reason];
}
[_backgroundManagedObjectContext unlock];
// complete the process on the main thread
if (currentRequest.error)
[self performSelectorOnMainThread:#selector(backgroundSaveProcessDidFail:) withObject:currentRequest waitUntilDone:NO];
else
[self performSelectorOnMainThread:#selector(backgroundSaveProcessDidSucceed:) withObject:currentRequest waitUntilDone:NO];
// clear out the request
currentRequest = nil;
}
}];
}
- (void)backgroundSaveProcessDidFail:(VS_CoreDataRequest *)request
{
if (request.error)
[self logError:request.error];
if (request.completionBlock)
{
void (^saveCompletionBlock)(NSArray *, NSError *) = request.completionBlock;
saveCompletionBlock(nil, request.error);
}
}
- (void)backgroundSaveProcessDidSucceed:(VS_CoreDataRequest *)request
{
// get objects from main thread
NSArray *objects = nil;
if (request.objects.count > 0)
{
NSFetchRequest *fetchReq = [NSFetchRequest fetchRequestWithEntityName:[NSString stringWithFormat:#"%#", request.managedObjectClass]];
fetchReq.predicate = [NSPredicate predicateWithFormat:#"self IN %#", request.objects];
objects = [self executeFetchRequest:fetchReq];
}
// call the completion block
if (request.completionBlock)
{
void (^saveCompletionBlock)(NSArray *, NSError *) = request.completionBlock;
saveCompletionBlock(objects, nil);
}
}
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
// create the MOC for the backgroumd thread
_backgroundManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_backgroundManagedObjectContext setPersistentStoreCoordinator:coordinator];
[_backgroundManagedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
_backgroundManagedObjectContext.undoManager = nil;
// create the MOC for the main thread
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setParentContext:_backgroundManagedObjectContext];
[_managedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
}
return _managedObjectContext;
}
Do any of you have any idea why this crash is happening?
** EDIT **
Ladies and gents I have found the solution. Apparently, even when using nested contexts you still have to merge the changes via the NSManagedObjectContextDidSaveNotification. Once I added that into my code it all started to work perfectly. Below is my working code. Thanks a million guys!
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil)
return _managedObjectContext;
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
// create the MOC for the backgroumd thread
_backgroundManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_backgroundManagedObjectContext setPersistentStoreCoordinator:coordinator];
[_backgroundManagedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
_backgroundManagedObjectContext.undoManager = nil;
// create the MOC for the main thread
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setParentContext:_backgroundManagedObjectContext];
[_managedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(mergeChangesFromContextDidSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:_backgroundManagedObjectContext];
}
return _managedObjectContext;
}
- (void)saveJsonObjects:(NSDictionary *)jsonDict
objectMapping:(VS_ObjectMapping *)objectMapping
class:(__unsafe_unretained Class)managedObjectClass
completion:(void (^)(NSArray *objects, NSError *error))completion
{
// perform save on background thread
[_backgroundManagedObjectContext performBlock:^(void)
{
// create a new process object and add it to the dictionary
VS_CoreDataRequest *currentRequest = [[VS_CoreDataRequest alloc] init];
currentRequest.managedObjectClass = managedObjectClass;
// save the JSON dictionary starting at the upper most level of the key path
NSArray *objects = [self saveJSON:jsonDict objectMapping:objectMapping class:managedObjectClass managedObjectContext:_backgroundManagedObjectContext level:0];
if (objects.count == 0)
{
currentRequest.error = [self createErrorWithErrorCode:100 description:#"No objects were found for the object mapping"];
[self performSelectorOnMainThread:#selector(backgroundSaveProcessDidFail:) withObject:currentRequest waitUntilDone:NO];
}
else
{
// save the objects so we can access them later to be re-fetched and returned on the main thread
[currentRequest.objects addObjectsFromArray:objects];
// save the object IDs and the completion block to global variables so we can access them after the save
currentRequest.completionBlock = completion;
[_backgroundManagedObjectContext lock];
#try
{
[_backgroundManagedObjectContext processPendingChanges];
[_backgroundManagedObjectContext save:nil];
}
#catch (NSException *exception)
{
currentRequest.error = [self createErrorWithErrorCode:100 description:exception.reason];
}
[_backgroundManagedObjectContext unlock];
// complete the process on the main thread
if (currentRequest.error)
[self performSelectorOnMainThread:#selector(backgroundSaveProcessDidFail:) withObject:currentRequest waitUntilDone:NO];
else
[self performSelectorOnMainThread:#selector(backgroundSaveProcessDidSucceed:) withObject:currentRequest waitUntilDone:NO];
// clear out the request
currentRequest = nil;
}
}];
}
- (void)mergeChangesFromContextDidSaveNotification:(NSNotification *)notification
{
[_managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}
- (void)backgroundSaveProcessDidFail:(VS_CoreDataRequest *)request
{
if (request.error)
[self logError:request.error];
if (request.completionBlock)
{
void (^saveCompletionBlock)(NSArray *, NSError *) = request.completionBlock;
saveCompletionBlock(nil, request.error);
}
}
- (void)backgroundSaveProcessDidSucceed:(VS_CoreDataRequest *)request
{
// get objects from main thread
NSArray *objects = nil;
if (request.objects.count > 0)
{
NSFetchRequest *fetchReq = [NSFetchRequest fetchRequestWithEntityName:[NSString stringWithFormat:#"%#", request.managedObjectClass]];
fetchReq.predicate = [NSPredicate predicateWithFormat:#"self IN %#", request.objects];
objects = [self executeFetchRequest:fetchReq];
}
// call the completion block
if (request.completionBlock)
{
void (^saveCompletionBlock)(NSArray *, NSError *) = request.completionBlock;
saveCompletionBlock(objects, nil);
}
}

Core data entity array generate crash on release or remove objects in IOS

This is my CoreDataManagerClass.
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface RTC_CoreDataManager : NSObject
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
-(void)insertEntity:(NSString *)entityName arrayOfManagedObject:(NSMutableArray *)array;
+(RTC_CoreDataManager *)shredInstance;
#end
#import "RTC_CoreDataManager.h"
RTC_CoreDataManager *obj_RTC;
#implementation RTC_CoreDataManager
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
- (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();
}
}
}
+(RTC_CoreDataManager *)shredInstance{
if (obj_RTC == nil) {
obj_RTC = [[RTC_CoreDataManager alloc]init];
}
return obj_RTC;
}
#pragma mark - Core Data stack
- (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:#"RTC" withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"RTC.sqlite"];
NSError *error = nil;
if (![[NSFileManager defaultManager] copyItemAtURL:storeURL toURL:[NSURL alloc] error:&error]) {
NSLog(#"Oops, could copy preloaded data");
}
__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;
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
-(void)insertEntity:(NSString *)entityName arrayOfManagedObject:(NSMutableArray *)array
{
NSManagedObjectContext *backgroundMOC = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
for (id object in array)
{
[backgroundMOC performBlockAndWait:^
{
NSError *error;
if (![__managedObjectContext save:&error])
{
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}];
}
}
#end
And this is my code in another controller.
-(void)viewDidLoad
{
[super viewDidLoad];
appDele_Obj = (RTC_AppDelegate *)[[UIApplication sharedApplication] delegate];
appDele_Obj.entityArray=[[NSMutableArray alloc]init];
for (int i=0; i<10; i++)
{
Survey *objSurvey = [NSEntityDescription
insertNewObjectForEntityForName:#"Survey"
inManagedObjectContext:[RTC_CoreDataManager shredInstance].managedObjectContext]; [objSurvey setFirstName:#"1"];
[objSurvey setLastName:#"2"];
[objSurvey setEmpId:#"3"];
[objSurvey setLanguage:#"Hindi"];
[objSurvey setCountry:#"India"];
[objSurvey setSurveyNo:[NSNumber numberWithInt:2]];
[[appDele_Obj entityArray] addObject:objSurvey];
[objSurvey release];
}
//[objSurvey release];
[[RTC_CoreDataManager shredInstance] insertEntity:#"Survey" arrayOfManagedObject:[appDele_Obj entityArray]];
if ([[appDele_Obj entityArray]count] >0) {
[[appDele_Obj entityArray] removeAllObjects];
}
}
So My question is,
If I call method removeAllObjects on [appDele_Obj entityArray] crashing the application. Why I can not call [[appDele_Obj entityArray] removeAllObjects];
in above approach. Any one can help me to solve this crash.
Thanks.
It's a simple case of memory mis-management. This creates an autoreleased object:
Survey *objSurvey = [NSEntityDescription
insertNewObjectForEntityForName:#"Survey"
inManagedObjectContext:[RTC_CoreDataManager shredInstance].managedObjectContext];
Then you do this:
[[appDele_Obj entityArray] addObject:objSurvey];
[objSurvey release];
You should not be calling release here. The object is autoreleased-- calling release is not only unnecessary, it's dangerous. Later on when you remove the objects from the array, you end up over-releasing every object in it. That causes the crash.
A few other things from the code:
Calling save: on a managed object context in a loop is unnecessary unless you're making new changes on each pass through the loop. Your insertEntity:arrayOfManagedObject: method is doing a lot of unnecessary work.
The array in viewDidLoad is not necessary or useful for what you're doing. You've created the objects, and they're in the managed object context. Once you finish setting the attributes of those objects, you don't need to keep references. Keep adding objects until you're done, then tell the managed object context to save.
It's a minor detail, but you named a method that creates a singleton shredInstance. "Shred" is almost exactly the opposite of what you're doing in that method. You probably meant sharedInstance.

iOS 5 Core Data duplicate row with multiple NSManagedObjectContext

Our table view controllers use an NSFetchedResultsController to show data from Core Data. We download new data in the background. When an entity is modified in the new data, on iOS 5.1.1 phone, we see that treated as a new row in the table instead of an update. Cannot duplicate on the iOS 5.1 simulator or an iOS 6 device.
The UIApplicationDelegate creates a NSManagedObjectContext with concurrency type NSMainQueueConcurrencyType. Our UITableViewController implements NSFetchedResultsControllerDelegate. In viewWillAppear we go fetch new data. In the method getting data, we create a second NSManagedObjectContext with concurrenty Type NSPrivateQueueConcurrencyType. We do a performBlock on that new context, and do the network call and json parsing. There's a NSFetchRequest to get the previous data, so we can delete the old objects, or modify any existing entities with the same id. After modify the existing entity or creating new ones, we then deleteObject the old entity objects. Then we save this private context. Then on the parent context, do a performBlock to save the changes there.
On iOS5.1, the table is incorrect. If we change on of the objects, instead of being modified, it is added to the table as a new row. If we leave this controller and come back to it, getting new data, it shows the right amount.
AppDelegate.m
- (void)saveContext
{
[self.privateWriterContext performBlock:^{
NSError *error = nil;
[self.privateWriterContext save:&error];
// Handle error...
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:self.privateWriterContext];
}];
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)privateWriterContext
{
if (__privateWriterContext != nil) {
return __privateWriterContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__privateWriterContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[__privateWriterContext setPersistentStoreCoordinator:coordinator];
}
return __privateWriterContext;
}
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil) {
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[__managedObjectContext setParentContext:self.privateWriterContext];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(saveContext:)
name:NSManagedObjectContextDidSaveNotification
object:__managedObjectContext];
return __managedObjectContext;
}
class that fetches from server
+ (void) fetchFromURL:(NSString *) notificationsUrl withManagedObjectContext (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *importContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
importContext.parentContext = managedObjectContext;
[importContext performBlock: ^{
NSError *error;
NSURLResponse *response;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSData *responseData = [NSData dataWithContentsOfURLUsingCurrentUser:[NSURL URLWithString:notificationsUrl] returningResponse:&response error:&error];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSMutableSet *newKeys = [[NSMutableSet alloc] init];
NSArray *notifications;
if(responseData) {
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSMutableDictionary *previousNotifications = [[NSMutableDictionary alloc] init];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Notification"];
NSArray * oldObjects = [importContext executeFetchRequest:request error:&error];
for (Notification* oldObject in oldObjects) {
[previousNotifications setObject:oldObject forKey:oldObject.notificationId];
}
notifications = [json objectForKey:#"notifications"];
//create/update objects
for(NSDictionary *notificationDictionary in notifications) {
NSString *notificationId = [notificationDictionary objectForKey:#"id"];
Notification *notification = [previousNotifications objectForKey:notificationId];
if(notification) {
[previousNotifications removeObjectForKey:notificationId];
} else {
notification = [NSEntityDescription insertNewObjectForEntityForName:#"Notification" inManagedObjectContext:importContext];
[newKeys addObject:notificationId];
}
notification.notificationId = [notificationDictionary objectForKey:#"id"];
//other properties from the json response
}
for (NSManagedObject * oldObject in [previousNotifications allValues]) {
[importContext deleteObject:oldObject];
}
}
if (![importContext save:&error]) {
NSLog(#"Could not save to main context after update to notifications: %#", [error userInfo]);
}
//persist to store and update fetched result controllers
[importContext.parentContext performBlock:^{
NSError *parentError = nil;
if(![importContext.parentContext save:&parentError]) {
NSLog(#"Could not save to store after update to notifications: %#", [error userInfo]);
}
}];
}
];
}
I suffered the problem recently too.
The problem is because of two contexts in different threads.
On device which is running iOS 5.1, merging them cause it to insert a new record instead of update it. I change the background thread to use main context instead and the problem is gone.
No clue why merging does not work in this particular case.

Resources