Tag Archives: NSDocument

My first Mac app

I decided to take a break from programming iOS apps, and wrote my first Mac OS X app today.  It was surprisingly simple.  It is based on the NSDocument class, and there is an Xcode template for this.  This template has all the menus, including cutting and pasting, formatting, etc, already built in and function. The main additions to the template were putting an NSScrollView in the window in the Document.xib file so I could edit some text, and adding some code to save and read files.

Of course, there were a few hiccups, which I mostly overcame:

  • The Document.h header file does not care about the NSScrollView; you need to hook it up to the NSTextView instead.  The formatted text sits within the text view, and can be accessed via the textStorage method. This has class NSTextStorage, which is a subclass of NSAttributedString.
  • The vaguely named dataOfType:error: method is for saving data, and the readFromData:ofType:error: method for reading data.
  • I posted the approach I used for reading and writing at Stack Overflow here, because I suspect the way I came up with is not guaranteed to work.
  • You should not set the text in the text view in the reading routine, because it may not exist yet.  Save it to an instance variable.  Set the text to this ivar in the windowControllerDidLoadNib: method.
  • I saved two icons, icon_128x128.png and docIcon_128x128.png, into my project.  In my <app name>-Info.plist I set the icon file to the first file name (including the .png), and under Document types, the Icon File Name to the second file name.  This associates those pictures with my app in some places (e.g. the about box, and within Xcode), but it does not ultimately set my app’s icon in the Finder.  How do I do this?
  • It was surprisingly hard to get the compiled program out of the Xcode environment and into a finished app that appears in the Finder on my Mac. The trick is to archive it, then press “Distribute…” (of course!).  You can choose to distribute it directly, and ad-hoc, and export as “Application”.