Search code examples
cocoansarraycontroller

How to access an Array Controller from App Delegate?


I have a simple Core Data based Cocoa app that uses an ArrayController to display model objects (employees). Two buttons allow for adding and deleting employees. The add button is wired with bindings to the insert: action of the Array Controller however the delete button is wired to a confirmDelete method in the App Delegate, which shows a modal confirmation dialog.

How do I get access in the confirmDelete method of the App Delegate to the Array Controller to remove the selected object from the Array Controller (and the underlying store)?


Solution

  • You can simply do like this-

    1. Bind array controller to app delegate

    2. In confirmDelete method, add this line after checking your conditions : [yourArrayController remove:nil];

    Hope this helps :)

    ---- Edit ----

    Please be sure to save the context after performing deletion, otherwise it will not be reflected in persistent store.

    ie. after this line:

    [yourArrayController remove:nil];
    

    Add this line:

    NSError *error = nil;
    if(![self.managedObjectContext save:&error]){
       NSLog(@"Some Useful Message!");
    }
    

    Generally, this code is used in - applicationShouldTerminate: , which automatically saves it to persistent store, when application quits.