Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data could not fulfill fault for object after obtainPermanentIDs

I'm getting data from a webserver, processing it on a child private background context called backgroundMOC. It is a child of a mainMOC which is linked to the main UI, so saving on the backgroundMOC triggers UI changes. The mainMOC is a child of a masterMOC which is a private background queue tied to the persistent store, so saving on the master saves to disk.

What I do now is receive data, create new objects on backgroundMOC, then save backgroundMOC (so that the UI updates), save mainMOC, (so that I can almost save to disk), and save masterMOC (so that I can finally write to disk). The problem is that when the object appears in the UI via a fetched results controller, the objectId is still a temporary one.

This causes problems with duplicate row issues, where if I receive the same data from the server (by accident), my backgroundMOC does not know that this object already exists because it has not been assigned a permanent id, so it creates another object. When I restart the app, the duplicate object disappears, so I know it's just an issue with id mapping.

So I thought I might try

[backgroundMOC obtainPermanentIDsForObjects:backgroundMOC.registeredObjects.allObjects error:nil];

before saving at all (I've tried after saving too). However, for some reason, calling this line throws an exception:

CoreData could not fulfill a fault for...

If you have any hints that might lead me in the right direction, please share. Thanks

Edit: Ok so initially I was calling obtainPermanentIDsForObjects on the backgroundMOC, which is a child of the mainMOC, which is a child of the masterMOC. I switched it so that I obtain the ids on the mainMOC, and it solved all my problems (for now). Was I never supposed to call obtainPermIds on the child context?

like image 529
Snowman Avatar asked Jul 04 '12 02:07

Snowman


2 Answers

This is a known bug (nested contexts not getting permanent IDs when new objects are saved)could, and supposed to be fixed in an upcoming release...

You should be able to ask for permanent IDs though, but you should only ask for them on the objects that have been inserted.

[moc obtainPermanentIDsForObjects:moc.insertedObjects.allObjects error:0];

You must do this before saving the MOC though, because if you save without obtaining permanent IDs, the temporary IDs are propagated to parent contexts. For example, in your case where you save to the mainMoc, then obtain the IDS, the backgroundMOC still has the temporary IDs, so future saves from it will create duplicate data.

Note that obtaining permanent IDs goes all the way to the database, but if you are doing it in a child MOC of the main MOC, you should not block the main thread at all while this is happening.

So, in your save from your lowest level MOC, you should effectively have something like this (with appropriate error handling, of course)...

[backgroundMoc performBlock:^{
    [backgroundMoc obtainPermanentIDsForObjects:backgroundMoc.insertedObjects.allObjects error:0];
    [backgroundMoc save:0];
    [mainMoc performBlock:^{
       [mainMoc save:0];
        [masterMoc performBlock:^{
            [masterMoc save:0];
        }];
    }];
}];

There are some other games you can play, if you want.

Provide a category on NSManagedObject similar to this...

@implementation NSManagedObject (initWithPermanentID)
- (id)initWithEntity:(NSEntityDescription *)entity insertWithPermanentIDIntoManagedObjectContext:(NSManagedObjectContext *)context {
    if (self = [self initWithEntity:entity insertIntoManagedObjectContext:context]) {
        NSError *error = nil;
        if (![context obtainPermanentIDsForObjects:@[self] error:&error]) {
            @throw [NSException exceptionWithName:@"CoreData Error" reason:error.localizedDescription userInfo:error.userInfo];
        }
    }
    return self;
}

+ (NSArray*)createMultipleObjects:(NSUInteger)count withEntity:(NSEntityDescription *)entity inManagedObjectContext:(NSManagedObjectContext *)context {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];
    for (NSUInteger i = 0; i < count; ++i) {
        [array addObject:[[self alloc] initWithEntity:entity insertIntoManagedObjectContext:context]];
    }
    NSError *error = nil;
    if (![context obtainPermanentIDsForObjects:array error:&error]) {
        @throw [NSException exceptionWithName:@"CoreData Error" reason:error.localizedDescription userInfo:error.userInfo];
    }
    return array;
}
@end

Now, in the first one, you are paying to go into the database and create an ID for each entity created, but it's not that much, and it's happening in a background thread, and each dip is short...

Oh well, it's not the best, but it has provided useful. In addition, the second creates multiple of the same object, and grabs their permanent IDs at the same time.

You can also use a MOC directly connected to the PSC, and watch for DidChange events, but that's the same as the old way.

Unfortunately, you can't have a separate MOC just make persistentID requests and pass the ObjectID, though you can have a separate MOC making prototype objects in the DB, and giving you the ObjectID of them.

A prototype factory is a fairly common pattern, and if you go that route, it's very easy to make a minor change when the eventual bug fixes get here.

EDIT

In response to Sven...

If you are creating new, complex graphs, then you need to obtain a permanent ID immediately after creation. To decrease the number of hits to the store, you should create them all, then obtain the IDs at once, then start hooking them up.

Honestly, all this is to get around the bugs that currently exist, which are worth working around for small-to-medium sized updates. Your code will be the same (sans the obtain) when the bugs are fixed. So, I suggest this method for smaller imports.

If you are doing a large scale update, I suggest using the "old" method. Create a new MOC directly connected to the PSC. Make all your changes there, and have your "live" contexts just merge from those DidSave notifications.

Finally, on the database impact of permanent IDs. It is OK to discard the MOC. The disk is hit, and the metadata is changed, but the objects are not persisted.

Honestly, I did not do a large test to see if there is any empty space as a result, though, so you may want to do that and get back with me.

Look at the actual database file size on disk, then create 10000 objects, then obtain persistent IDs, release the MOC, and look at the size again.

If there is an impact, you can try deleting the objects, or run a vacuum on the database after large updates to see if that works.

If you are going to be creating lots of objects that you may just throw away, then there is no need to hit the database. You may want to just attach directly to the PSC and use the old faithful notifications.

like image 118
Jody Hagins Avatar answered Nov 06 '22 02:11

Jody Hagins


I had experienced a variety of frustrations with Core Data when working between foreground and background threads. In searching for a resolution for one of my issues I ran across

Magical Record

I spent a bit of time going through documentation and the methods and I can say it has really made working with Core Data much easier. Specifically it will also help manage multiple contexts and threads for you.

You might want to check it out.

like image 1
radesix Avatar answered Nov 06 '22 03:11

radesix