Fogmeister
Fogmeister

Reputation: 77641

Correct use of MagicalRecord to save in BG

I've seen two different ways of doing this and I'd like to know which is correct.

Specifically I'm talking about accessing the ManagedObject on the BG thread.

The methods I have seen are...

Person *person = ...
[MagicalRecord saveUsingBlock:^(NSManagedObjectContext *localContext) {
    Person *localPerson = [person inContext:localContext];
    // do stuff...
}]

But I've also seen...

Person *person = ...
NSManagedObjectID *objectID = person.objectID;
[MagicalRecord saveUsingBlock:^(NSManagedObjectContext *localContext) {
    Person *localPerson = (Person*)[localContext objectWithID:objectID];
    // do stuff...
}]

The latter seems more correct as you're not trying to access the object across threads. But having seen both I wasn't sure if MagicalRecord did something Magical to get around this?

Upvotes: 2

Views: 1812

Answers (1)

Martin R
Martin R

Reputation: 539775

inContext: is a Magical Record "shorthand" for MR_inContext:, and that is implemented as

- (id) MR_inContext:(NSManagedObjectContext *)otherContext
{
    NSError *error = nil;
    NSManagedObject *inContext = [otherContext existingObjectWithID:[self objectID] error:&error];
    [MagicalRecord handleErrors:error];

    return inContext;
}

(see https://github.com/magicalpanda/MagicalRecord/blob/master/MagicalRecord/Categories/NSManagedObject/NSManagedObject%2BMagicalRecord.m).

So both are valid methods to access the object across different contexts, one using existingObjectWithID and the other objectWithID. For the subtle differences between these see the documentation or e.g. What's the difference between -existingObjectWithID:error: and –objectWithID:?.

Upvotes: 2

Related Questions