Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create multiple objects in background?
    primarykey
    data
    text
    <p>I'm using MagicalRecord 2.0.3 and I can't really figure out how to save data in the background. </p> <p>According to the documentation, something like this should work:</p> <pre><code>[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext) { // Do this hundreds of times [MyObject createInContext:localContext]; }]; </code></pre> <p>However, nothing is saved to the database. I've seen multiple people posting solutions similar to this:</p> <pre><code>[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext) { // Do this hundreds of times [MyObject createInContext:localContext]; } completion:^{ [[NSOperationQueue mainQueue] addOperationWithBlock:^{ [[NSManagedObjectContext defaultContext] saveNestedContexts]; }]; }]; </code></pre> <p>This does save my data in the database, however since the save happens on the main thread, my application is unresponsive for a while (with my dataset, about 3 seconds which is way too long).</p> <p>I've also tried this, but it also blocks up while saving:</p> <pre><code>self.queue = [[NSOperationQueue alloc] init]; [self.queue addOperationWithBlock:^{ NSManagedObjectContext *localContext = [NSManagedObjectContext contextForCurrentThread]; // Do this hundreds of times [MyObject createInContext:localContext]; [localContext saveNestedContexts]; }]; </code></pre> <p>And lastly, same blocking effect with this code:</p> <pre><code>dispatch_queue_t syncQueue = dispatch_queue_create("Sync queue", NULL); dispatch_async(syncQueue, ^{ NSManagedObjectContext *localContext = [NSManagedObjectContext contextForCurrentThread]; // Do this hundreds of times [MyObject createInContext:localContext]; [[NSManagedObjectContext contextForCurrentThread] saveNestedContexts]; }); </code></pre> <p>So, what is the best way to solve this? I need to create hundreds of objects in the background and the app needs to remain responsive.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload