views:

19

answers:

2

Hello experts,

I have a question about Core Data. When starting my appliction, when is my data (which is stored automatically by Core Data) loaded into the NSArrayControllers? I want to modify it in the first place before the user can interact with it.

To be more specific: I have an NSArrayController for the entitity Playlist. Before the user can add new playlists or interact with the app at all, I want to modify the playlists programmatically. I tried windowControllerDidLoadNib: in my NSPersistentDocument (MyDocument.m) and awakeFromNib both in my NSPersistendDocument and the NSArrayController, but when I check in these methods with [[myArrayController arrangedObjects] count] I get 0 as result (the array controller's content is empty).

However, I actually have data stored and it is displayed to the user. I just do not know when and where I can modify it in the first place.

Thank your for any help.

A: 

You could try observing the "arrangedObjects" keypath of the controller and adding some logic to work that your array controller has been populated for the first time.

Another possible hook is implementing the awakeFromInsert/awakeFromFetch methods of your managed objects.

Warren Burton
+1  A: 

Data is never "loaded" into the NSArrayController. The array controller is not an array itself. It does not contain or otherwise store data.

Instead, the array controller queries the object it is bound to for specific pieces of data only when that specific data is needed. This is especially true of Core Data in which managed objects are only fully instantiated when their attributes are accessed. The array controller moves data from an array type data structure to another object (usually an UI element.)

If you want to modify an existing store before it displays in the UI, you need to process the data before the array controller used by the UI is even initialized. If you're using NSPersistentDocument, then you can override readFromURL:ofType:error: to fetch and modify all your objects when the document is first opened. Alternatively, you can override the window controller's windowWillLoad or showWindow methods.

Regardless of where you do it, you must fetch all the managed objects you want to modify. You could programmatically create an array controller to do this but a fetch request is easier to micro manage if you have a large number of objects to modify.

TechZen
Thank your very much! I now recognize that I need to fetch the managed objects I need to modify beforehand myself. That's exactly what I wanted to know and it now works for me! Thanks.
Core