How do I use a subclass of NSDocumentController in XCode 4?

前端 未结 7 1442
陌清茗
陌清茗 2020-12-31 11:34

I am currently in the process of trying to teach myself Cocoa development. Toward this end, I purchased a mostly-excellent book, Cocoa Recipes for Mac OS X: Vermont Reci

7条回答
  •  爱一瞬间的悲伤
    2020-12-31 11:49

    Here's a solution:

    // In MyDocumentController.h
    @interface MyDocumentController : NSDocumentController
    @end
    
    // In MyDocumentController.m
    @implementation MyDocumentController
      // ... your custom code here
    @end
    
    // In MyAppDelegate.h
    @interface AppDelegate : NSObject 
    @property (nonatomic, strong) IBOutlet MyDocumentController *myController;
    @end
    

    Now, go into MainMenu.xib and add a custom object to your nib. Be sure to use the inspector on this object, and in the third pane of the inspector, set the custom class to MyDocumentController.

    Now wire this object into your outlet by ctrl-clicking on your new object in the left list of things in the nib and drag (while still ctrl-clicking) to App Delegate. Release and it should flash and show myController. Click that and you're all set.

    Now you can test that you're getting your custom controller with the following code:

    // In MyAppDelegate.m
    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSLog(@"sharedController is %@", [NSDocumentController sharedController]);
    }
    

    This should print something like

    
    

    You're done!

    The key is to wire in your custom MyDocumentController in MainMenu.xib. If you try to just initialize it in applicationDidFinishLaunching, it's often too late and AppKit has already created and set sharedDocumentController (of which there can only be one).

    Also, the outlet needs to be strong not weak because your custom controller is a top-level object in the nib not referenced by anything else in the nib.

    This works for me on multiple versions of OS X and Xcode.

    Please mark this as the correct answer if it works for you! :-)

提交回复
热议问题