0

It seems I tried everything but it seems it works in main thread only. For example:

[SomeClass MR_createEntity];
[[NSManagedObjectContext MR_defaultContext] MR_saveWithOptions:MRSaveSynchronously completion:^(BOOL success, NSError *error) {

        if (success) {
            NSLog(@"You successfully saved your context.");
        } else if (error) {
            NSLog(@"Error saving context: %@", error.description);
        }
    }];

If this code is run in main thread then success == YES otherwise (in background thread) it gives success == NO. In both cases error == nil.

So is it impossible to call the saving in background thread?

Gargo
  • 1,135
  • 1
  • 10
  • 21
  • The default context is the main thread context. Perhaps you mean the [NSManagedObjectContext MR_saveWithBlock:] method? – Daniel Galasko Aug 24 '14 at 19:29
  • this library is very strange. Now it works... every second time. Why?! checked everything and the problem is with library – Gargo Aug 25 '14 at 16:56

2 Answers2

1

Completion blocks are always called from the main thread, here's an example that should work:

Person *person = ...;

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext){

  Person *localPerson = [person MR_inContext:localContext];
  localPerson.firstName = @"John";
  localPerson.lastName = @"Appleseed";

} completion:^(BOOL success, NSError *error) {

  self.everyoneInTheDepartment = [Person findAll];

}];

Reference: https://github.com/magicalpanda/MagicalRecord/blob/master/Docs/Working-with-Managed-Object-Contexts.md

ObjSal
  • 1,494
  • 1
  • 14
  • 18
0

Finally I hadn't to create a workable project with fully background MagicalRecord work.

The best solution for me is to update database in the main thread only and to read the database in any thread (including background). Additionally I show custom progress view on database updating.

Gargo
  • 1,135
  • 1
  • 10
  • 21