3
votes

I want to build a document-based app in Cocoa but so that it can create and handle different types of documents. Think Word, Excel, Powerpoint all in one application, only much simpler. But every window will be different based on the type of document.

For storage I will use CoreData. I think of adding a field that specifies the type of document since they should all have the same file ending.

So without creating several independent apps what would be the best way to go about it? How do I create this in Interface Builder? How do I code this up?

I don't need detailed source code or anything, just the general idea of how to do this, I will figure the rest out.

Thanks in advance!

2

2 Answers

15
votes

This is something the Cocoa Document system is explicitly designed to do. Apple provides documentation, but here are the highlights.

  • Each kind of document is a subclass of NSDocument. If you're using Core Data, base your class on NSPersistentDocument instead. (Apple has a basic tutorial on how to use Core Data in a document-based application)
  • You tell Cocoa about the kinds of documents your application can open, and which document class to use, with the Info.plist.
  • Each NSDocument subclass has one or more NSWindowController objects associated with it, each of which represents a single window. If you'll only have a single window, you don't have to subclass NSWindowController. You can put your UI logic in your document subclass. However, for cleaner code, I'd strongly recommend subclassing NSWindowController.
  • NSWindowController (and NSDocument if you decide not to subclass NSWindowController) can load a window from a NIB you build in Interface Builder. In fact, this is the recommended approach for creating your document windows.

Hopefully this gives you a general idea of how to approach this in Cocoa.

1
votes

You would start by creating a NIB for each of your document types; and an NSDocument subclass for each (use an existing document-based-app-example-NIB for the setup here). You would then set theses classes to handle your various document types in the property list of the application; insofar as I remember, there are some useful tools for this hidden somewhere in XCode.

Once that is up an running, most of the details should be handled automagically; but you might still have to fudge the File-menu about a bit, and I seem to remember there being some trouble with setting the default document type and whatnot.

On the whole, tho', it's not a lot more complex than creating an app for a single kind of documents.

PS: Do take care to ensure that you really need different filetypes; sometimes it might be more appropriate having several different views of the same file. Just a thought. :)