drekka
drekka

Reputation: 21883

MagicalRecord creating won't save new data object.

I have this code:

HLMReferenceData *referenceDataObj = [HLMReferenceData createEntity];
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext){
    HLMReferenceData *localReferenceData = [referenceDataObj inContext:localContext];
    // Setup localReferenceData here ....
}
                  completion:NULL];

As far as I can see this is exactly in line with the examples on the net of how to create a new record using MagicalRecord. However it does not work. I get this in the log:

... +[MagicalRecord(ErrorHandling) defaultErrorHandler:](0x3abdc4) Error Message: The operation couldn’t be completed. (Cocoa error 133000.)
... +[MagicalRecord(ErrorHandling) defaultErrorHandler:](0x3abdc4) Error Domain: NSCocoaErrorDomain
... +[MagicalRecord(ErrorHandling) defaultErrorHandler:](0x3abdc4) Recovery Suggestion: (null)
... -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x954b680) NO CHANGES IN ** UNNAMED ** CONTEXT - NOT SAVING

I've dug around inside Magical Record's codebase and the error occurs when the inContext: method is called. It returns a nil object as a result. I've searched the web and have not been able to figure out what is wrong. The HLMReferenceData class is mapped to a single table in the data model with no links to other tables. All the fields in the class get populated.

I'm at a loss.

Upvotes: 2

Views: 1219

Answers (1)

Peter E
Peter E

Reputation: 4931

inContext: is returning nil because your object was created/inserted in the outer context, and never saved. Therefore it is not yet accessible in the localContext. (More specifically, inContext: will try look up the object using a temporary objectID, and it won't find one.) You should create/insert the object inside the save block, like this:

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext){
    HLMReferenceData *referenceDataObj = [HLMReferenceData createEntityInContext:localContext];
    referenceDataObj.name = @"foo";
    // Continue setting up referenceDataObj here ....
} completion: NULL];

You can see a very similar example on Magical Record's github docs, under Saving. See the subsection 'Changes to saving in MagicalRecord 2.3.0'

https://github.com/magicalpanda/MagicalRecord/blob/develop/Docs/Saving.md

Upvotes: 2

Related Questions