Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

ios - Core Data: Do child contexts ever get permanent objectIDs for newly inserted objects?

I have an app with two managed object contexts setup like this:

  • Parent Context: NSPrivateQueueConcurrencyType, linked to the persistent store.
  • Main Context: NSMainQueueConcurrencyType, child of Parent Context.

When insert a new managed object to the main context, I save the main context and then the parent context like this:

[context performBlockAndWait:^{
    NSError * error = nil;
    if (![context save: &error]) {
        NSLog(@"Core Data save error %@, %@", error, [error userInfo]);
    }
}];

[parentContext performBlock:^{
    NSError *error = nil;
    BOOL result = [parentContext save: &error];
    if ( ! result ) {
        NSLog( @"Core Data save error in parent context %@, %@", error, [error userInfo] );
    }
}];

My understanding is that when the manage object is first created, it has a temporary objectID. Then the main context is saved and this object, with its temporary ID, gets to the parent context. Then the parent context is saved. When this last context is saved, the temporary objectID in the parent context gets transformed into a permanent objectID.

So:

  • Does the permanent object ID ever get propagated automatically back to the main (child) context?
  • When I force to get the object permanent ID with [NSManagedObjectContext obtainPermanentIDsForObjects:error:], then background the app, reactivate it, reload, get the object using main context's objectWithID:, and access a property, I get

    "CoreData could not fulfill a fault for ...".

What is wrong with this approach? See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is a known bug, hopefully fixed soon, but in general, obtaining a permanent ID is sufficient, provided you do so before you save the data in the first child, and you only include the inserted objects:

[moc obtainPermanentIDsForObjects:moc.insertedObjects.allObjects error:&error]

In some complex cases, it is better to get a permanent ID as soon as you create the instance, especially if you have complex relationships.

How and when are you calling obtainPermanentIDsForObjects?

I do not follow the part about the app crashing. Maybe a better explanation would help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...