Search code examples
macoscore-dataosx-snow-leopard

How do I send a message, at application launch, immediately after a core data entity is loaded?


The method applicationDidFinishLaunching:, is called in the app delegate prior to the loading of a Core Data entity into a table created with the "Core Data Entity" tool in the Interface Builder Library.

I have a custom view (with controller) that charts data based on the selected Core Data entity. When I launch my application, the top entry in the table of Core Data entities automatically is selected and other text fields bound to properties of that entity are populated with the correct data. I need to send a message to the custom view controller to redraw the custom view after the data is loaded at application launch.

Where should I put the code to send the message to the custom view controller? Is there a delegate method similar to applicationDidFinishLaunching: that receives a notification after the core data entity is loaded at launch?


Solution

  • It took me a while to figure this out since I'm relatively new to Cocoa. The appropriate documentation is here: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdBindings.html

    If the "automatically prepares content" flag (see, for example, setAutomaticallyPreparesContent:) is set for a controller, the controller's initial content is fetched from its managed object context using the controller's current fetch predicate. It is important to note that the controller's fetch is executed as a delayed operation performed after its managed object context is set (by nib loading)—this therefore happens after awakeFromNib and windowControllerDidLoadNib:. This can create a problem if you want to perform an operation with the contents of an object controller in either of these methods, since the controller's content is nil. You can work around this by executing the fetch "manually" with fetchWithRequest:merge:error:. You pass nil as the fetch request argument to use the default request, as illustrated in the following code fragment.

    I added an IBOutlet to my NSArrayController within the app delegate and connected it in Interface Builder. I then added the following to the method applicationDidFinishLoading: based on the documentation in the aforementioned link:

    -(void)applicationDidFinishLaunching:(NSNotification *) aNotification {
    
        NSError *error = nil;
        BOOL ok = [myArrayController fetchWithRequest:nil merge:NO error:&error];
    
        if (ok) {
            [myCustomViewController redrawMyCustomView];
        }
    }
    

    Now, when I launch the application, the data populates the table and the view automatically is redrawn with the selected data.