Reputation: 2600
I'm trying to save an object inside the AFNetworking block, but SOMETIMES it crashes with error: CoreData could not fulfill a fault for...
I've read that it's related when I try to manage an object data when it was deleted from the persistent store.
How can I avoid this?
Example:
Line *line = [Line MR_createEntity];
[line setSync:@(SYNC_PROCESSING)];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://test.com/request" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// CRASH
[line setSync:@(SYNC_SUCCESS)];
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
} failure:nil];
Upvotes: 0
Views: 155
Reputation: 69687
You're trying to perform a background operation. The defaultContext is for the main thread only (it's not clearly documented, we're working on that). But what you want to do is perform your save in a context that will handle the background thread operations for you. That is, you want to use a NSManagedObjectContext that works on the background. In general try this:
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
id myObject = [line MR_inContext:localContext];
[myObject setSync:@(value)];
}];
This will let MagicalRecord create the proper background context for your data to operate on when it tries to save data. MagicalRecord will set up much of the cruft needed in order to start using Core Data. Just let it do much of the work and you'll be on your way.
Upvotes: 1