saveInBackgroundWithBlock, the correct way to access created objects in completion.. #276

Closed
morgz opened this Issue Oct 14, 2012 · 2 comments

Comments

Projects
None yet
3 participants

morgz commented Oct 14, 2012

Hi There,

I wanted to check whether this is the correct workflow.

I create multiple objects. Save them in the background and then do some stuff with them on the completion block. My issue was trying to get references the specific objects created, in the completion block.

The solution i have come up with is. It is just frustrating me that the objects in collectEntities can't be fulfilled in the completion block without refetching:

__block NSMutableArray *collectedEntities = [[NSMutableArray alloc]initWithCapacity:proxies.count];

[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext){

    for (ProxySite *proxy in proxies) {

        NSError *parsingError = nil;
        //Object is created or updated
        Site *entity = [self parseProxy:proxy batchSave:true inContext:localContext withError:&parsingError];


        [collectedEntities addObject:entity];

    }

} completion:^{

    // I couldn't just access collectedEntities as they seem to be faults which cannot be fulfilled. All the values were nil

   // I then go about fetching the previously saved items in the main threads context
    NSMutableArray *ids = [[NSMutableArray alloc]initWithCapacity:collectedEntities.count];

    for (Site *site in collectedEntities) {
        [ids addObject:[site objectID]];
    }

    NSPredicate *filter = [NSPredicate predicateWithFormat:@"(self IN %@)", ids];

    NSMutableArray *newSites = [NSMutableArray arrayWithArray:[Site MR_findAllWithPredicate:filter]];

    //New sites contains all the previously created or updated records.. success
    successBlock(newSites);

}];
Member

blackgold9 commented Oct 15, 2012

Remember that the objects were created on a background thread, and can only be accessed there. The object ID's are valid though, and your approach is correct. Requerying them on the main thread should be pretty cheap as they are already loaded into core-data's cache. Feel free to respond with any other questions you might have.

blackgold9 closed this Oct 15, 2012

I am running into something very similar. What I had to do was call [[NSManagedObjectContext MR_defaultContext] refreshObject:object mergeChanges:YES] for each main thread object in order to retrieve their updated values from another background context. I couldn't find an alternative. Any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment