Shared Objects in Cocoa - cocoa

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. =)

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).

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.

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.

Related

MVC theory/Cocoa: where to create model?

I have an AppDelegate, an NSWindowController and some Views. What is the best place to define DataModel * data;, initialize [[data alloc] initWithSomething] etc.?
I suppose it must be done in WindowController (.h and .m), since model must be handled by the main controller. Am I right? I've got a small doubt about keeping a pointer to Model in AppDelegate...
Sorry if my terminology is not MVC-correct, I'm just studying...

How to access an object's NSDocument?

I can access an app-wide delegate instance using [NSApp delegate] after adding an NSObject to the mainmenu.xib, setting the name of the object to the name of my appDelegate and setting the mainmenu.xib delegate to this object.
Now, what I would like to do, is to access to an object's Document, i.e. the active NSDocument that the object "belongs" to. It would be a doc-wide delegate instance I guess. Sometimes [self document] works, but not always. Is there a generic way?
There is no need to pass a reference explicitly. You may access the document from NSViewController in the following way:
id document = self.view.window.windowController.document;
What about [[NSDocumentController sharedDocumentController] currentDocument] ?
Be careful nevertheless.
Please read
NSDocumentController currentDocument returning nil
For any sub windows that are part of the document, it turns out that it's very easy to make a very simple subclass of NSViewController and store the required information in there. These view controllers are set up within the main Document implementation so it is easy to pass the address of the NSDocument object. Any actual subview can then be controlled by a view controller that is a subclass of this "managing controller".
This solution does not work for every object, but it does take the biggest hurdle and solves my problem...

NSWindowController subclass initialization from a nib doesn't use -initWithCoder:?

I've added a custom subclass of NSWindowController to my Cocoa project, and added an instance of my subclass to my application's nib. I expected to see my override of the -initWithCoder: method called when the nib was loaded, but it was not. To debug, I added a regular -init method and set a breakpoint on it — and sure enough I hit the breakpoint while loading the nib.
This could actually make some things simpler for me (e.g. setting the windowNibName) but I don't understand why Cocoa is behaving this way. All the documentation I have read suggests that -initWithCoder: is where I should be overriding. Why is this case any different?
I'm assuming that to instantiate your window controller in Interface Builder, you dragged a generic NSObject instance to the nib file, then assigned your custom NSWindowController subclass as the object's class, is that correct? If so, then I think they key difference going on here is that you're dealing with instantiating a generic object rather than a custom object included in one of IB's palettes.
Most of the time, when you create and configure an object using IB, the settings that you specify in the various inspectors gets encoded using the encodeWithCoder: method when the nib file gets saved. When you then load that nib file in your application, those objects get initialized using the initWithCoder: method.
However, in the case of that generic object instance, Interface Builder doesn't necessarily know anything about the class of the object being instantiated. Since you can specify any class name at all to be instantiated, if you specify a class that IB doesn't have loaded via a palette or framework, there's no way it can serialize that object using NSCoding. So I believe that when you instantiate a generic object like that, it gets initialized using init rather than initWithCoder: because it wasn't saved using encodeWithCoder: in the first place when the nib file was saved.
I don't know if this is documented anywhere, but I think that's why you're seeing a difference there. I also don't think it's specific to NSWindowController, but rather you'd see the same behavior from any object instantiated as a generic NSObject in IB, regardless of the specific class.
I still don't have a formal answer why Cocoa behaves this way, but in practical use it seems to be convenient. I have defined an NSWindowController subclass with the following -init method and it works like a charm.
- (id)init;
{
if ((self = [super initWithWindowNibName:#"MumbleMumbleSheet"]) != nil) {
…
}
return self;
}
If -initWithCoder: were being called I would have to figure out how to fulfill the implicit obligation to call the super -initWithCoder: method and still get the right -windowNibName used for loading. It's much more straightforward this way.
I would still appreciate a pointer to some documentation that says this class is different and explains why and how… But in the absence of documentation there is empirical evidence.
The coder methods are used for classes that have been serialised and saved to file.
What you are doing here is different. You are building your controller class into your executable. This means that there's no need to read the class itself from file as it's a part of the running application binary.
When using this controller class you need provide an init method where you provide the nib file name. Why? Well, you have the compiled class as a part of your exe but no knowledge about what the nib file is. This is how you provide that knowledge.
Think of it this way. You controller class is a part of the exe. Some link between it and the nib file needs to be made. One way would be to scan through all the nib files looking for references to this controller. That would be inefficient. Provide the name in the init and everything bootstraps.
In other words you have learnt some important lessons from your experiments. Well done, on being so observive.

Cocoa: what is the var name of an instance created by a NIB file?

When a Cocoa NIB file instantiates an instance of a custom controller object, what is the name of the variable that that custom controller instance is assigned to?
In case that isn't clear, if you manually created an instance of that class you would do:
MyControllerClass *myVar = [[MyControllerClass alloc] init];
What equivalent of "myVar" has the NIB used when doing this behind the scenes?
There is no such thing as a variable name once the app is compiled, so this question doesn't make much sense. In your example, myVar is just a convenient label for you, the programmer, and does not exist in any way once your source code is compiled into binary code.
When you place an object into a nib file, it is archived and then unarchived at runtime. If you want to be able to get a reference to an object that has been archived in a nib file, you need to use an outlet, which means you declare an IBOutlet instance variable in a class that is present in the nib file and then connect that outlet to the object in the nib you want to reference in Interface Builder. Instance variables are different to the stack variable that you declared in your example and can be referred to at runtime.
Typically you would have an object that "owns" a nib. Normally nibs are loaded by an instance of NSWindowController or NSViewController and window or view controller is represented in the nib file as File's Owner. If you declare outlets in your window/view controller, you can then connect the outlets from File's Owner to your object in Interface Builder.
So, to clarify, you need a reference to your object in the nib from some other object in the same nib. That second object declares an outlet using the IBOutlet keyword on an instance variable like so:
#interface SomeOtherObject : NSObject
{
IBOutlet SomeObject* anObject;
}
#end
In Interface Builder, you can then connect the anObject outlet of the SomeOtherObject instance to the first SomeObject instance. You can do this by control-dragging from one object to another or you can do it in the connections panel in the Interface Builder inspector.
You can then refer to your SomeObject instance by the variable name anObject inside the code for SomeOtherObject.
Implement the awakeFromNib method in your controller class - it's called immediately after the nib has finished loading, and your controller's instance can be found in the "self" variable.
# tedge (I can't make comments to your answer):
Can you clarify for a beginning Cocoa learner a bit. Take the Apple Currency Converter tutorial.
I implement the awakeFromNib method in the existing ConverterController class. (Something I will be learning to do shortly!)
The app starts up and an instance of ConverterController is automatically instantiated.
What will awakeFromNib tell me about that running instance (other than that it's ready to use) -- and what syntax with "self" gets it to divulge that information?
… what is the name of the variable that that custom controller instance is assigned to?
It's whatever name you gave that variable when you declared it.
IB doesn't create variables for you. It sounds like you're after an outlet, which is a variable you create that IB knows about and lets you plug objects into, thereby setting the variable.
(You actually can create outlets from IB, and in the modern runtime, this should really create the outlet, not just declare a non-existent outlet in the nib. Even this way, though, you create the outlet [in IB] and you give it a name.)
I think what's Nibbles is confused about is that how to reference the variable defined only in NIB file from code.
the answer to that is, normally you have a custom controller class (or delegate class) A in code and NIB, and if you have another class or controller B only defined in NIB, just setup a outlet in A pointing to B. Since A can be used anywhere in your code, B can be accessed as well through A then.
I had this question as well.

IBOutlet not getting set in Cocoa MVC project

I might not be using IBOutlet correctly, or some other subtlety with how NIB files work is causing me trouble - any help would be much appreciated (feel free to propose an alternate way to accomplish what I want).
I have a View object and a Controller object. Both are in the NIB. The Controller's init is also called when the NIB is loaded and the View is initialized in the 'awakeFromNib' callback.
I need a way to connect these two objects - specifically, enable the 'View' object to call functions on the Controller.
Based on documentation online, the way to get these connected is to define an IBOutlet in the View and connect it to the Controller in the Interface Builder. So i created an
IBOutlet Controller* _controller;
in the View interface and graphically connected it to the Controller object in Interface Builder by making a connection from the View to the Controller and assigning the _controller outlet to the Controller (the blue Generic Object box in Interface Builder).
At runtime though, _controller is always _nil. I have verified that the Controller's init was indeed called.
Is there something obvious I'm missing about this?
Any simpler way to connect these two? Since they're both created by the NIB I don't have a common object that has a pointer to both.
Try accessing the IBOutlet in viewDidLoad instad.
When awakeFromNib is called not all the IBOutlets are populated (even though the documentation seem to imply it).

Resources