New Core Data object doesn't show up in NSArrayController arrangedObjects

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-02 05:48:06

问题


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

回答1:


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).




回答2:


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!



来源:https://stackoverflow.com/questions/4538704/new-core-data-object-doesnt-show-up-in-nsarraycontroller-arrangedobjects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!