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
NSObjectinstance to the nib file, then assigned your customNSWindowControllersubclass 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 theinitWithCoder: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 usinginitrather thaninitWithCoder:because it wasn’t saved usingencodeWithCoder: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 genericNSObjectin IB, regardless of the specific class.