4
votes

When I insert a new object in a Core Data managed object context and shortly after that try to find this new object in the NSArrayController (which is connect with the managedObjectContext through binding), I can't find it. I do the creation and search in one method.

My question now. How long does it take for a new inserted object to show up in the NSArrayControllers arrangedObject array?

Update: Here is the code for inserting and fetching the new objects

NSEntityDescription *entity = [[[self managedObjectModel] entitiesByName] objectForKey:@"EntityName"];
NSManagedObject *object = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:[self managedObjectContext]];
...
[[self managedObjectContext] processPendingChanges];

[arrayController fetch:nil];
NSArray* objects = [arrayController arrangedObjects]; //the new object is not present in the array
2

2 Answers

3
votes

It's not a matter of "how long" but "at what point". There's enough of a distinction that it's important to study it. :-)

Usually array controllers are automatically updated (re-fetch their contents in this case) on the next run-loop but technically "at some future run loop". If you want them to update immediately after inserting something, send your MOC a -processPendingChanges then ask the array controller to -fetch:.

Among the first things you read in the Core Data documentation is that it's an advanced Cocoa topic whose prerequisite knowledge includes Key Value Binding and Key Value Observing. The missing bit of knowledge that led you to this question is found in understanding of KVC/KVO (and the Cocoa Bindings layer).

0
votes

Just found a fix for this. I use the setSelectedObjects: method of the NSArrayController to select the object. Don't know why I didn't used this method anyway!