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.
Related
I am using CoreData in my app and I have two main entities, let's say Cats and Dogs.
I have this method that I use to initialise my context:
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
It refers to this method in my App Delegate:
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
Now, at some point, I have to update some data in my Cats entity.
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Cats"];
NSMutableArray *catsArrayData = [[context executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSManagedObject *aCat = [catsArrayData objectAtIndex:i];
NSMutableArray *catsArray = [aCat valueForKey:#"cat"];
[catsArray addObject:responseData];
[aCat setValue:catsArray forKey:#"cat"];
NSError *error = nil;
[context save:&error];
Then, I want to do the same for my Dogs entity. So I use the same code, but for the dogs entity. It's in another part of my code, so I have to redefine:
NSManagedObjectContext *context = [self managedObjectContext];
But the problem is that even though I save this second context, it is actually not saved. The data isn't there. How can I resolve this issue?
You need implement your own change notification mechanism, This is good source to learn it. Multi-Context CoreData.
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];
}
When my app loads it give that notification that its using local store: 1 usually it takes 4 to 5 minutes before it returns using local store :0. Not only that reloading using NSNotifications does not seem to work although going to a new view then back does.
appDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if(![[NSUserDefaults standardUserDefaults] boolForKey:#"firstTime"]){
UIAlertView *msg = [[UIAlertView alloc] initWithTitle:#"Would You Like to Keep Clients Synced With iCloud" message:nil delegate:self cancelButtonTitle:#"NO" otherButtonTitles:#"YES", nil];
msg.tag = 101;
[msg show];
}
[self registerForiCloudNotifications];
UINavigationController *nc = (UINavigationController *)self.window.rootViewController;
ClientListViewController *iC = (ClientListViewController *)[nc viewControllers][0];
iC.context = [self managedObjectContext];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
- (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]);
abort();
}
}
}
#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] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_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:#"Benjii" 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;
}
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self storeURL] options:[self storeOptions] error:&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.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
#{NSMigratePersistentStoresAutomaticallyOption:#YES, NSInferMappingModelAutomaticallyOption:#YES}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
-(NSURL *)storeURL{
return [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Benjii.sqlite"];
}
- (void)registerForiCloudNotifications{
NSLog(#"Registering");
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:#selector(storesWillChange:)
name:NSPersistentStoreCoordinatorStoresWillChangeNotification
object:self.persistentStoreCoordinator];
[notificationCenter addObserver:self
selector:#selector(storesDidChange:)
name:NSPersistentStoreCoordinatorStoresDidChangeNotification
object:self.persistentStoreCoordinator];
[notificationCenter addObserver:self
selector:#selector(persistentStoreDidImportUbiquitousContentChanges:)
name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
object:self.persistentStoreCoordinator];
}
#pragma mark - iCloud Support
//Use these options in your call to addPersistentStore:
-(NSDictionary *)storeOptions{
NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
[options setObject:#"GraniteCloudStore" forKey:NSPersistentStoreUbiquitousContentNameKey];
return options;
}
- (void) persistentStoreDidImportUbiquitousContentChanges:(NSNotification *)changeNotification{
NSManagedObjectContext *context = self.managedObjectContext;
[context performBlock:^{
[context mergeChangesFromContextDidSaveNotification:changeNotification];
}];
[[NSNotificationCenter defaultCenter] postNotificationName:#"Reload" object:nil];
}
- (void) storesWillChange:(NSNotification *)notification {
NSManagedObjectContext *context = self.managedObjectContext;
[context performBlockAndWait:^{
NSError *error;
if([context hasChanges]){
BOOL success = [context save:&error];
if(!success && error){
//perform error handling
NSLog(#"%#", [error localizedDescription]);
}
}
[context reset];
}];
//Refresh User Interface
NSLog(#"Stores will change");
}
-(void)storesDidChange:(NSNotification *)notification{
//Refresh your User Interface
NSLog(#"Stores did change");
[[NSNotificationCenter defaultCenter] postNotificationName:#"Reload" object:nil];
}
-(void)migrateiCloudStoreToLocalStore{
//assuming you only have one store.
NSPersistentStore *store = [[_persistentStoreCoordinator persistentStores] firstObject];
NSMutableDictionary *localStoreOptions = [[self storeOptions] mutableCopy];
[localStoreOptions setObject:#YES forKey:NSPersistentStoreRemoveUbiquitousMetadataOption];
NSPersistentStore *newStore = [_persistentStoreCoordinator migratePersistentStore:store
toURL:[self storeURL]
options:localStoreOptions
withType:NSSQLiteStoreType
error:nil];
[self reloadStore:newStore];
}
-(void)reloadStore:(NSPersistentStore *)store {
if(store){
[_persistentStoreCoordinator removePersistentStore:store error:nil];
}
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[self storeURL]
options:[self storeOptions]
error:nil];
}
#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];
}
#pragma mark - Alert View Delegate
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
if(alertView.tag == 101){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"firstTime"];
if(buttonIndex != alertView.cancelButtonIndex){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"iCloudSupport"];
}
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
#end
and fetchresultcontroller:
-(NSFetchedResultsController *)clientResultsController{
if(clientResultsController != nil){
return clientResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Client"];
// NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name beginswith %#"];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"finitial" ascending:YES selector:#selector(localizedCompare:)];
//[fetchRequest setPredicate:predicate];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
NSFetchedResultsController *theFetchedResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:context
sectionNameKeyPath:#"finitial"
cacheName:#"Root"];
self.clientResultsController = theFetchedResultController;
self.clientResultsController.delegate = self;
return clientResultsController;
}
and observer in view Controller:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserverForName:#"Reload"
object:self
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note){
NSLog(#"Reloading");
[self reloadFetchedResults:note];
}];
}
Sorry if the answer is really simple i checked the other similar questions and they were either unanswered or Outdated (though I tried a couple of them anyway). Any help will be much appreciated
edit
it seems like my observer isnt catching the observerForName:#"Reload"
does anyone know how to add an observer to the method that sends this message:
PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:: CoreData: Ubiquity: mobile~843477F1-43D0-4E72-BD91-26C3276A9212:GraniteCloudStore
Using local storage: 0
also noticed that if I wait until the above message then rotate the screen also causes table to populate however the persistentStoreCoordinatorDidChange is called before that notice
I'm having a similar issue here, but in my case, when I migrate my app from a non-icloud version to an iCloud version, the existing data does not show. Though if I add a new entry, then everything shows and with a debugging, I realised why everything is showing.
In my UITableView, I did the following:
- (void)reloadFetchedResults:(NSNotification*)note {
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
if (note)
{
[self.timelineTableView reloadData];
}
}
In my viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reloadFetchedResults:) name:#"RefetchAllDatabaseData" object:[[UIApplication sharedApplication] delegate]];
// In your case, the name would be Reload
- (void)viewDidUnload
{
[super viewDidUnload];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Try this - I'm a complete noob here but this worked for me to be able to see changes straight away.
This code is supposed to save my data to core data in TestViewController.m file:
//Property
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
//Methods
- (void)saveUser:(NSString *) username withEmail:(NSString *) email withName:(NSString *) name
{
//1
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
//2
self.managedObjectContext = appDelegate.managedObjectContext;
User *coreDataUser = [NSEntityDescription insertNewObjectForEntityForName:#"User" inManagedObjectContext:self.managedObjectContext];
coreDataUser.username = username;
coreDataUser.email = email;
coreDataUser.name = name;
NSError *error;
if (![self.managedObjectContext save:&error])
{
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
//In my save user method I have stuff that is done in another thread but then this is called:
// Add in any UIKit code here on main queue
dispatch_async(dispatch_get_main_queue(), ^{
if (isUnique == YES)
{
[self saveUser:[emailStr lowercaseString] withEmail:emailStr withName:nameStr];
My code always crashes on:
ser *coreDataUser = [NSEntityDescription insertNewObjectForEntityForName:#"User" inManagedObjectContext:self.managedObjectContext];
It says signal SIGABRT in main.
I am following this tutorial: http://www.codigator.com/tutorials/ios-core-data-tutorial-with-example/
And running in ios 7.
What am I missing?
I'm tracing the appDelegate.m code now but it looks like this:
// 1
- (NSManagedObjectContext *) managedObjectContext {
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_ managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return _managedObjectContext;
}
//2
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
_managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return _managedObjectModel;
}
//3
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil)
{
return _persistentStoreCoordinator;
}
NSString *test = [self applicationDocumentsDirectory];
NSString *test2 = test;
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"HappyPeople.sqlite"]];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
i f (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error])
{
/*Error for store creation should be handled in here*/
}
return _persistentStoreCoordinator;
}
- (NSString *)applicationDocumentsDirectory
{
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
Seems like the sqllite db file gets created.
The exception I am getting is this:
NSException * name:#"NSInternalInconsistencyException" reason:#"+entityForName: could not locate an entity named 'Users' in this model." 0x0895ee20
I know this question is a little old...
This is the exception I get when I change the schema of the object model and try to use a file with the old schema. The sqllite db on disk may not match your apps schema.
I have been using CoreData with a UIManagedDocument so it is a little different. There you have options to automatically migrate on the open.
Also, early on in the comments it was asked whether the ManagedObjectContext was nil. I believe that this should be checked before you call the insert. Are we sure all of the core data setup is on the main queue? It can take a little time to open. (Again with UIManagedDocument is explicitly on another thread.)
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);
}
}