Question

Can anyone explain why given the following MagicalRecord import code

__block NSManagedObject *importedObject = nil;

[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
  id entityClass = NSClassFromString( name );
  importedObject = [entityClass importFromObject:dictionary inContext:localContext];
}];

NSManagedObjectID *importedObjectID = importedObject.objectID;

NSManagedObject *relatedObject = ( (CustomRelatedExampleObject *) [[NSManagedObjectContext defaultContext] objectWithID:importedObjectID] ).relatedObject;

This works fine, setting the relationship and saving as expected

[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
        someObjectInDefaultContext.alsoRelated = relatedObject;
}];

But this causes exec bad access, when I expected that this is technically more correct because I am using the local context for saving my data. (Note: I left out the code that gets objectIDs from both objects for brevity)

[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
        AnotherCustomExampleObject *localSomeOtherObjectInDefaultContext = (AnotherCustomExampleObject *) [localContext objectWithID:someOtherObjectInDefaultContextObjectID];
        CustomRelatedExampleObject *localRelatedObject = (CustomRelatedExampleObject *) [localContext objectWithID:localRelatedObjectID];
        localSomeOtherObjectInDefaultContext.alsoRelated = localRelatedObject;
}];

I get exec bad access on the last line when I try to assign the object to the relationship in the other object.

UPDATE 1

This problem was caused by using temporary object ids when getting local copies of the objects in another managed object context.

UPDATE 2

I have discovered that simply changing the method used to retrieve the object removes the error.

[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
    AnotherCustomExampleObject *localSomeOtherObjectInDefaultContext = (AnotherCustomExampleObject *) [localContext existingObjectWithID:someOtherObjectInDefaultContextObjectID];
    CustomRelatedExampleObject *localRelatedObject = (CustomRelatedExampleObject *) [localContext existingObjectWithID:localRelatedObjectID];
    localSomeOtherObjectInDefaultContext.alsoRelated = localRelatedObject;
}];

using existingObjectWithID instead of objectWithID returns and object with a permanent id instead of a temporary one.

Was it helpful?

Solution

Check your object ids. If one or both are temporary, core data will not like that. But, in general, the crash you describe is because you are trying to relate two objects from a different context. I know you're going through the proper steps here, but perhaps double check in the debugger to make sure the context on those objects are the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top