views:

662

answers:

3

Hey guys.

I'm working with CoreData in Cocoa (not document-based). My problem is, that I want to access the SAME NSArrayController from different NIBs. But every NIB has an own instance of this NSArrayController.

My question is now how I could generate sharedObjects (like the NSUserDefaultsController). It would help me a lot. Thanks for your answers. =)

+2  A: 

I'm not really sure trying to reuse NSArrayController is the best choice (I'd need to know more about your project, but I've never ran into a situation where I'd do something like that), but you can use a static variable inside a class method like so:

+ (id)sharedObject;
{
    static id object = nil;

    if ( object == nil )
    {
     object = [[self alloc] init];
    }

    return object;
}

Keep in mind that this is not a true singleton, since you can still allocate additional objects of that class. You can use this guide if you really want to be strict.

Marc Charbonneau
+3  A: 

You generally don't want to share an NSArrayController between nibs. It's probably better to have multiple NSArrayController (one per NIB) which are all bound to the same underlying model. If you want this model (e.g. an NSArray) to be application global, you can expose it via the NSApplication's delegate (e.g. instantiate your custom MyAppDelegate class in MainMenu.nib and connect the NSApplication's delegate outlet to the instance of your MyAppDelegate class). In other NIBs, you can then bind an NSArrayController's contentArray binding to Shared Application.delegate.myArray (assuming MyAppDelegate exposes—via KVC-compliant methods—an NSArray binding called myArray). You are essentially using IB and the MainMenu.nib to create your singleton instance of MyAppDelegate.

Keep in mind that this approach makes unit testing your application difficult, since there are now singletons in the object graph that you can't mock or stub out during testing. It would be much better to create an NSWindowController or NSViewController for each secondary (non MainMenu.nib) NIB and bind the NSArrayControllers in those nibs to File Owner.myArray. You can then instantiate the NSWindowController or NSViewController, passing it an array (or array KVC-compliant object) before loading the secondary NIB. In this way, you can test the functionality of the nibs in isolation (using a mock or stub for the array).

Barry Wark
+1  A: 

Matt Gallagher has a good post on singletons and other ways to have "global" data over on his blog you may want to check out too. It's a little more clear than Apples documentation, and has a link to a header file that makes it nice and easy to create singletons out of almost any Cocoa class.

I'm actually using his header file in some of my projects, and it works great.

Shawn Craver