Search code examples
core-dataswiftcocoa-bindings

Need to use second window using Cocoa Bindings and Core Data in Swift


I have recently started experimenting with Xcode following the introduction of Swift. I have no background in Objective C, but I am making progress, especially with Cocoa Bindings and Core Data. I am playing around with an OSX application which has one xib and one window and is bound to a Core Data model. So far everything works just fine and I can populate a Table View with no issues.

My next step is to include a second window with another Table View bound to my Core Data model. I found this impossible to achieve because I couldn't access the AppDelegate when I tried to bind the second Table View to the Core Data model.

So I tried to create a second window in the MainMenu xib; now binding is possible but it seems to be very clumsy. Surely a second window demands its own xib and, if so, how on earth do I bind to the AppDelegate?

My goal is to use Coocoa Bindings as far as possible to eliminate "glue code", but all my research only reveals Objective C examples, some of which are very old, involve a huge amount of program code and are not at all relevant to Xcode v6.1.

I'm a newbie to Xcode, but so far I love it and would appreciate any advice or assistance.


Solution

  • The single-coordinator application template adds that "App Delegate" object to the MainMenu.Xib, and it's somewhat magically connected to the NSApplication object's delegate, in that the App Delegate object is created by the Nib loading process and attached to the NSApplication instance. It's fairly impossible to duplicate that object in another Nib. You can really create havoc trying to do so.

    The simplest way to do what you want in any other Nib is to bind to the Application with a keypath beginning with "delegate." Voila, you have what you want.

    Others will insist that the delegate object shouldn't own the core data stack, and you should move all that boilerplate code to some other place. Or, that each view controller should be passed the MOC pointer as a property (see comments below)... but that's not really relevant to this question.

    YMMV, this answer is given from the Objective-C universe, but the language shouldn't matter.