I have a NSManagedObject
(File) with some properties and I wrote some code that downloads a file with AFNetworking
based on the information in this NSManagedObject
- the download works fine!
Now I want to change some MetaData in the completion block
and save the changes to CoreData
using Magical Record
. This basically works, except I have to restart the App to get the new values of the NSManagedObject
- And this is the problem. During one lifecycle I'm not able to get the updated NSManagedObject
. I even tried to refetch the object...
I don't understand, why I would have to restart to App to get the updated information? Is there a context
issue? I don't see it.
I get the File Object from the defaultContext
:
NSManagedObjectContext *managedObjectContext = [NSManagedObjectContext MR_defaultContext];
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:@"File" inManagedObjectContext:managedObjectContext]];
And here's my download method:
- (void)downloadFile:(File*)fileObject {
...
completionBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
File *localFile = [fileObject MR_inContext:localContext];
localFile.downloadStatus_ = [NSNumber numberWithInt:DownloadStatusCompleted];
}];
NSLog(@"State: %@"fileObject.downloadStatus_);
}
}
Update: I changed the line and it worked. I'm puzzled. I would guess, that localContext should actually be the current context. Which should be the one the object's.
File *localFile = [fileObject MR_inContext:localContext];
to
File *localFile = [fileObject MR_inContext:[NSManagedObjectContext MR_defaultContext]];
I figured out what happened and wanted to post the answer.
It turned out that a property of the NSManagedObject *fileObject was changed without saving it, in advance of calling the completionBlock! The StoreCoordinator tries to merge and save the changed property (within the completionBlock) - but this operation failed since the original object from the context was changed...