WWDC or bust

June 5th, 2009

Thanks to the generosity of Rogue Amoeba, the Ford Foundation, and listeners like you, I’ll be attending WWDC this year. If you want to find me there, I’ll be the one wearing a Rogue Amoeba T-shirt.

Actually, I’ll be one of the ones wearing a Rogue Amoeba T-shirt. The cute one.

No, sorry, that’s Paul. Let’s face it: in our fab four, I’m the Ringo. (Or for you younger folks, the Michael Anthony.) My plan is to earn millions hanging out with those other guys and making thumping noises in the background.

This will be my first time attending WWDC. I’m really looking forward to meeting fellow developers such as Rainer Brockerhoff and … umm … err … yeah. Anyway, hope to see you there!

To those poor, unfortunate souls who won’t be at the Moscone Center on Monday, I offer a consolation: the official 2009 WWDC keynote home game! The rules are straightforward. (1) Whenever Phil Schiller says something, drink. Heavily.

Radar Bug Friday: Bonus Edition

March 13th, 2009

Though Apple Bug Friday has gone the way of Rip and Robert Van Winkle, I’m bringing it back for one last, glorious, remunerative show. Opening act: some weird dancing fool who people last admired in the 80s. Take your choice.

The continuing failure of Apple to provide a searchable bug database has forced developers to take matters into their own hands. Witness Open Radar. I’ve never been one to join any club that would have me as a member — nor have I been one to be invited to any clubs — so I’ve decided to host my own list of bugs. Keep in mind that these are not all of the Radar bugs I’ve ever filed. They’re not even all of my currently unfixed bugs. They are, however, a very large subset of my currently unfixed bugs. (I’d say the cardinality is somewhere between aleph-null and aleph-one.)

For legal, moral, and comical reasons, I’ve edited the bugs to remove confidential information. I’ve also left out the embarrassing nude photos I attach for ADC. (I would stop uploading them, but engineering always requests more.) I hope that you find these bugs useful and also enjoy reading them as much as I enjoyed writing them. In fact, it’s a metaphysical certainty that you will enjoy reading them at least that much.

After imparting this vital information, I leave you to go in, through, and beyond … for coffee and a donut.

dSYM in your bundle or just happy to see me

January 20th, 2009

It’s been a while since I posted last. Rest assured that I did survive the Y2K9 disaster, though not unscathed. Since bloggers and other entertainers — such as Brian Williams — are required by law to offer a retrospective at the end of a year, I’ve been scanning the Top 10 lists of Top 10 lists of things that we have gained and lost in 2008. Next to our collective sanity, the most significant loss of the year was STABS. Actually, it wasn’t so much lost as deprecated. This means that we can’t expect any new features (or bugs!), and support for STABS debugging symbols may disappear in some future operating system, say, Windows -400. (I assume that the countdown of version numbers from 95 to 7 is intended to accurately represent the software’s regression.) In the transition from STABS to DWARF, it was thought (by the people who matter, viz., me) that we also lost the ability to ship debugging symbols with our apps. Luckily, it was discovered (again, by the people who matter) that we did not lose this ability.

Developers sometimes need to give users a debug version of an application. For example, a user may be experiencing an exception or crash that the developer cannot reproduce. Including debugging symbols with the app allows the reports to be fully symbolized. With STABS, the symbols reside within the app’s executable, so shipping them is trivial. The DWARF with dSYM format, on the other hand, puts the debugging symbols in a separate file. (To be accurate, a separate file within a separate bundle, but we’ll ignore that fact for this sentence.) By default, Xcode creates MyApp.app.dSYM in the same folder as MyApp.app, and indeed, Leopard’s crash reporter can locate MyApp.app.dSYM in the same folder as MyApp.app regardless of which folder they’re in on disk. Theoretically, then, you could have the user put a .dSYM in the same folder as the app. However, making the user do this would be, in a word, lame. In two words, pretty lame. Moreover, it doesn’t work at all on Tiger. Pretty, pretty lame.

When I face an insoluble problem, my tendency is to step back and get philosophical. Why do I exist? Why does the universe hate me? Who was the real Darrin? More to the point: what is an app? Essentially, an app is a command-line tool in a box with a pretty bow. (Another iSweater, just what I needed!) An app’s main executable file is located in the directory Contents/MacOS of the .app bundle. You can even launch an app from the command line, e.g.,

/Applications/Safari.app/Contents/MacOS/Safari

assuming that you haven’t deleted Safari for security reasons. So how does this information help us? It doesn’t — I’m just killing time here. However, it’s worth noting that if you build the Release configuration of a command-line tool project, Xcode by default creates MyTool.dSYM in the same folder as MyTool. In both Leopard and Tiger, the crash reporter can locate the .dSYM there. Thus, you would expect that the crash reporter can also locate MyApp.app/Contents/MacOS/MyApp.dSYM when your app crashes. And you would be right! (Of course, you would expect this because I just told you, whereas originally you would have expected to try a bunch of stuff and fail, like putting MyApp.app.dSYM in MyApp.app/Contents/MacOS.)

The beauty of this technique is that it works not only for the app’s main executable but also for other embedded executables such dynamic libraries and frameworks. When a crash occurs involving MyFramework.framework, the crash reporter will find

MyApp.app/Contents/Frameworks/MyFramework.framework/Versions/A/MyFramework.dSYM

You can build the framework in a separate Xcode project and copy the product along with its embedded dSYM into your app’s bundle, and the symbols will be found at crashtime. (That’s runtime with a bang.) In Tiger, the line numbers of the source code files can sometimes be a little off in the crash reports; this may be due to bugs in the handling of stripped binaries by atos, which I mentioned in my earlier post.

Now that we know where to put the debugging symbols in the app bundle, how do we get them there? Manual copying is unthinkable (like giving David Pogue a copy of OS X GM before ADC members, or putting Leon Panetta in charge of the CIA). If your entire build process is not automated, you should give up software development immediately and look for another career; I recommend professional ice dancing. You could write a shell script to copy MyApp.app.dSYM from the build directory, but that’s only slightly less annoying than having your users copy it to /Applications, because it’s something that Xcode should do itself.

Fortunately, the Xcode build setting reference tells us how to configure this. Or so one would think. Well, at least the relevant build settings are found in the environment variables … after you’ve written your shell script. The Xcode build transcript normally doesn’t show environment variables, but you can add a run script build phase to your target and check the option “Show environment variables in build log”. The environment variables reveal the default values for DWARF_DSYM_FOLDER_PATH and DWARF_DSYM_FILE_NAME, which Xcode uses in creating the dSYM file. Although you won’t find them in the target’s list of build settings, you can create them yourself in the User-Defined section. To embed the dSYM within the app bundle, just set DWARF_DSYM_FOLDER_PATH to $(CONFIGURATION_BUILD_DIR)/$(EXECUTABLE_FOLDER_PATH) and DWARF_DSYM_FILE_NAME to $(EXECUTABLE_NAME).dSYM. These settings should work for both apps and frameworks.

My beard has grown longer over the course of this post, and my knees are starting to ache, so it’s time to wrap it up, tip my hat to the new year, and meet the new boss.

Review of PGP boot disk encryption

November 23rd, 2008

This is my first official software review. I normally don’t review software other than my own — Radioshift, five thumbs up, buy now! — because there’s no profit in it (like US auto makers). However, Dave Dribin asked me to do it, and apparently Dave gets whatever he asks for.

PGP Whole Disk Encryption introduced pre-boot authentication for Intel Macs in version 9.9. Pre-boot authentication allows you to encrypt your Mac’s entire internal hard drive. I wrote a form of whole disk encryption myself in Knox, but that was for non-boot disks. Prior to installing PGP 9.9, I had been using Apple’s built-in FileVault to encrypt the home directory of my MacBook Pro. I became interested in whole disk encryption for the laptop after I discovered that neither third-party developers nor Apple itself could be trusted not to write personal data outside your home directory.

This review is not intended to be comprehensive, because again, I’m not being paid for it … though if a certain corp whose name is a certain acronym would send a certain something my way, I would certainly be appreciative, wink, wink, nudge, nudge, say no more. Before you charge the software to Mr. Underhill’s American Express card (want the number?), I highly recommend that you study the user guide for important caveats. My aim is simply to describe my experience and to pass along some undocumented tips I picked up along the way.

I purchased Whole Disk Encryption for Mac, affectionately known as WDE4M, from PGP’s online store for 119 US Dollars (more than a bread box, less than a nano), and I received my license key by email within 10 minutes, so no problems there. It took slightly longer to encrypt my boot disk. The entire process required around 8 hours for the MBP’s 200 GB internal HD. (Actually, according to Mac OS X, it’s 186.3 GB. These are sometimes given the label GiB, which stands for Grrrr, ithoughtihadmore Bytes.) Obviously, you’ll want to let it to run overnight, unless you need a break from watching your grass grow.

In reviewing WDE4M, the first concern is security. When you boot your Mac from the internal drive, you get the PGP login screen. At this point, the Mac OS X volume has not yet been mounted. Until you enter your password at the PGP login screen, the entire boot volume remains encrypted. As long as you choose a good password (mine is Joshua), all of your data is safe. Note that it is still possible to boot your Mac from a different disk such as a DVD or an external hard drive. It’s even possible to boot into Firewire target disk mode (assuming you have a Firewire port: ha, ha!). However, you won’t be able to mount the Mac OS X volume on the internal drive, because without PGP running, you have nothing more than a partition full of encrypted bytes. Indeed, PGP modifies the partition table of your disk to add its special boot partition, so I would recommend starting with a single volume of data. I previously had multiple partitions and volumes on the MBP, but I found that to be a PITA regardless of PGP.

After you authenticate successfully at the PGP screen, the computer boots normally into Mac OS X. It is crucial to realize that when you’re booted into Mac OS X, your data is vulnerable. PGP will decrypt on the fly any bytes that the OS asks for. Thus, if someone steals your laptop while it’s running OS X, you’re screwed. You can try logging out or setting a screensaver password, but those types of protection can often be defeated. The only way to guarantee safety is to shut down or reboot. Thankfully, WDE4M protects against so-called ‘cold boot’ attacks (unlike FileVault).

The next issue for WDE4M beyond security is performance. On my MBP with a 2.33 GHz Intel Core 2 Duo and 2 GB RAM, I’ve found performance to be a non-issue. Admittedly, I’ve never done speed tests, but I don’t perceive my system to be sluggish or slower from PGP WDE. It seems as ZippyTM as ever. I’ve heard from some sources (e.g., the shoe shine guy) that PGP’s encryption / decryption is much faster than FileVault’s. The only operations that seem a little slow are copying extremely large, multi-GB files from another disk; the entire contents of these files must be encrypted as they’re copied onto the internal drive.

The final issue I’ll discuss is backups. If you care about your data, you must back it up, otherwise you will lose it at some point. If your data is important enough to protect with WDE4M, it’s important enough to back up. (Note that I made two full backups of my internal drive before attempting to encrypt it. I also downloaded my brain into an android.) No backup strategy is perfect for everyone, so we must each follow one that fits our needs. For example, the majority of computer users follow the strategy that experts term ‘Divine Intervention’. I had to experiment quite a bit before I found something that worked for me: in the end I turned to good ol’ dd.

My procedure for backing up my PGP-encrypted internal hard drive is simple. Even a caveman could do it. (Yes, Unix has been around that long.) First I mount an external backup drive that has enough free space to fit my entire internal drive. Then I boot into the Mac OS X installer: this can be done from a partition on the external drive, from a DVD, or from a USB stick. A Mac OS X installer volume is not required to perform the backup — you could use another Mac, for example — but I use an installer so that I can boot from the MBP and take advantage of its Firewire 800 port. Finally I launch Terminal and enter the following:

dd if=/dev/disk0 of=/Volumes/backups/disk0.dmg

Running dd takes 5 to 7 hours back up the MBP’s 186 GiB HD to a FireWire 800 external HD. I might be able to expedite the process by tweaking the bs operand of dd, but I’m running the backup overnight anyway, so I favor simplicity and reliability over speed. Afterward, I have a byte-for-byte backup of my entire internal drive. Any machine running PGP can mount the dmg with the correct password, so the backup is suitable for file-based restoration. A machine without PGP installed, in contrast, will fail to mount the dmg, finding no mountable file systems, because the entire file system is encrypted.

From a security standpoint, a byte-for-byte backup is not ideal, because it has the same encryption key as the original. Once you start modifying files on your internal drive again, it’s conceivable that a diff between the backup and original could reveal something interesting. However, few people in the world have any hope of success in extracting readable information through such an investigation, certainly not the casual thief, and of course backing up your files unencrypted would be infinitely worse! I’m not trying to keep any state secrets (my WMD is curled up sleeping on his cat bed), but if you’re the paranoid type — and my hidden video cameras show me that you are — you should be able to encrypt your backup drive with a different key before you create the dmg with dd. Indeed, you could create one big encrypted dmg with Disk Utility and put the backup dmg inside it. I haven’t tried this myself, so I’d be interested to hear whether it’s viable. Anyway, this Russian doll approach would provide ample protection if your data were stolen by the Russian mafia, or if you were a member of it.

In the event of catastrophic data loss, e.g., my laptop is swallowed by a whale, I can use the backup to easily transform some other disk into a bootable clone of the laptop:

dd if=/Volumes/backups/disk0.dmg of=/dev/disk1

If you have an external drive the same size or slightly larger than your internal drive, you can skip the dmg and create a bootable clone directly:

dd if=/dev/disk0 of=/dev/disk1

The disadvantage of this procedure is that any extra space on the backup drive would be unusable. I have a few 500 GB (465 GiB, sigh) external HD’s, so it makes more sense for me to save multiple backups on each drive.

You can boot a clone of your PGP-encrypted drive from another machine regardless of whether the machine has PGP installed on its internal drive. However, it may take a couple of spontaneous reboots before you can login to Mac OS X, much like a software update, so you need to be patient. (Perhaps it’s updating the boot cache?) Also, booting the clone from the original machine is to be avoided. As a test of my backup procedure, I cloned my MBP to an external drive and then booted the MBP from the clone. The MBP did successfully boot from the external drive, and I was able to login to Mac OS X, but I was surprised to find that the Mac OS X volume was mounted from the internal rather than the external drive. This bizarre behavior puzzled me until I read Secrets of the GPT, which I already mentioned in my last post. The technical note warns, “Be careful when doing a block-for-block copy of a GPT disk. The GUID in the partition table header that identifies the disk (and the GUIDs in each partition entry) are meant to be globally unique, and Apple’s system software relies on this feature.” If you do what I did, “the computer might boot from either the original or the copy in an unpredictable fashion (perhaps toggling from boot to boot).” Oops! That reminds me of the time I got mount to show two volumes with the same BSD name … but that’s a tale for another day.

WDE4M comes with PGP Desktop, which has a number of useful features such as handling public-private key-pairs and allowing encryption of AOL Instant Message sessions between PGP users. PGP Desktop can automatically encrypt email as well, but one thing to look out for is that it attempts this by default. I kept getting “Invalid Authentication Certificate” warnings in Mail.app, and I initially blamed this on Leopard, because the warning window did not indicate that it was from PGP, and I had just installed Leopard prior to installing PGP. You can turn off the email encryption feature in the Messaging Security preferences of PGP.app. Hopefully PGP will put its name on the warning window in the next software update to PGP 9.9, so that it’s clear to the user where the warning is coming from.

Overall, in summary and conclusion, to wrap it all up, finally: I find WDE4M to be a well-engineered product, it does what it’s supposed to do, viz., protect all of your data, I have no regrets about buying it, and I have no reservations about encouraging other people to buy it too.

P.S. If you like WDE4M from PGP, you might also enjoy Airfoil from Rogue Amoeba. Nudge, nudge, say no more.

What about Sony?

November 2nd, 2008

Yesterday I purchased an 8 GB Sony Micro Vault USB drive.

USB drive

I’m sure it’s a fine device, though it’s far too early at this point to comment on its functionality. What I found immediately noteworthy was the packaging.

The drive came encased in a hard plastic tomb roughly ten times its size.

Front of package

Why such a large package for such a small item? The answer lies on the back.

Front of package

Not an inch to spare! Clearly, the size of the package was justified by the need for operating instructions on the back. Or important warnings before use. Or something? Actually, it’s not clear at all, because the font is ridiculously tiny.

If we take a close-up, we can see that the text does indeed provide us with instructions and warnings…

Front of package

…for opening the package. In seven languages, no less. And what do those instructions tell us?

Use scissors.


Postscript: You would think that finding the right storage size for your needs would be easy. The Finder told me that the files I wanted to put on the USB drive were 7.1 GB. Thus, an 8 GB drive should be plenty big. Right? Right?

For some reason that escapes me and that has somehow, astonishingly, escaped class action lawsuits, the drive manufacturers and the operating system manufacturers count GB differently. The capacity of my Micro Vault is 8,019,509,248 bytes, which according to Sony is 8 GB but according to Apple is 7.5 GB. Well, ok, so I lost half a gig right out the box, but I still have more than I need. Right? Right?

The USB drive came with a Master Boot Record partition scheme for Windows machines. This was no good for my purpose, because I was going to boot Intel Macs from the drive. Thus, I repartitioned in Disk Utility with a GUID Partition Table scheme, which is used by Intel Macs. When I was done, I was shocked to discover that the drive now contained less free space than I need for my files! What happened?

The answer can be found at Secrets of the GPT. Apple considers my USB drive to be a “big disk”. (Have they seen the photo above?) As a consequence, they ignored my choice of one partition in Disk Utility and added a second, 200 MB partition on the drive for EFI device drivers, although Apple does not currently use it for anything. Moreover, they added 128 MB of empty space after my main partition to make it easier for future system software to manipulate the partition map in ways that we can’t anticipate currently. That’s great for my great-grandchildren, but at present, I want that space.

My workaround for the problem was to reformat the drive using an Apple Partition Map scheme. This takes up less space on my “big disk”. Although APM is used by PowerPC Macs, it turns out that Intel Macs can boot from an APM drive too.

If APM didn’t work, I was going to use scissors.

Working without a nib, Part 7: The empire strikes back

October 20th, 2008

I recently received an email from Steve Jobs. He told me that he has read all of my blog posts. I found this ridiculous, so I replied, “You’re full of it!” Shockingly, he wrote back. “Actually,” he said, “all of the new apps of the past few years are nibless.” He then described the Apple-sanctioned technique of writing a nibless application.

In previous posts of this series, I was forced to use obscure workarounds such as +[NSObject poseAsClass:] and method_exchangeImplementations() to prevent NSApplicationMain() from trying to load a nib. Jordy Rose of Belkadan Software suggested to me that the easiest way to prevent NSApplicationMain() from trying to load a nib would be to avoid calling NSApplicationMain() at all. Instead, you would just call -[NSApplication run]. However, I was worried that NSApplicationMain() might do something else important (like phone home to get permission to launch). We don’t know, because we don’t have the source code.

I’m still waiting for the source code, but Steve did indicate that it was safe to skip NSApplicationMain(). Thus, there’s no need for tricksy runtime manipulation, except perhaps to prove your mad programming skills. Mad, that is, in the sense of having worn one ring for too long. Steve also affirmed that our call to -[NSApplication setAppleMenu:], a method that Apple removed from the API, will continue to work until there’s a replacement API. Indeed, Apple is working on some kind of replacement. Excellent! /me plays air guitar. So if you’re counting at home, it’s now (1) Exchange support and (2) Nibless support.

He didn’t mention the Open Recent menu, so it appears that my ugly hack is still required for non-document-based apps. This cannot be considered part of the Apple-sanctioned technique, though it is sanctioned by me, which is more desirable, because my approval comes in seven delicious flavors. I’ve updated Nibless for Leopard in light of Steve’s revelations and am making version 2.0 available for immediate download. This is major progress, because it already puts me two versions ahead of VLC.

So long, Steve, and thanks for all the fish!

Cocoa memory management for smarties, Part 3: accessors

October 5th, 2008

This post is not over until Minnesota Fats says it is, or until I figure out why he played in Iowa. In the meantime, let’s talk about getters and setters. A setter is distinguished by the prefix set, while a getter is distinguished by not having the prefix get. Got it? Getters and setters come in pairs; collectively, they are commonly known as accessor methods, less commonly as American Airlines or pocket rockets.

Accessor methods provide encapsulated access to an object’s instance variablesinstancvariabls for short. If your instancvariabl is an Objective-C object (in Freudian terms, an id), your accessors should almost always look like this:

-(id) thing
{
	return [[_thing retain] autorelease];
}

-(void) setThing:(id)aThing
{
	if (_thing != aThing)
	{
		[_thing release];
		_thing = [aThing retain];
	}
}

You can copy rather than retain in setThing: if the class of aThing conforms to <NSCopying>.

It may seem redundant to [[_thing retain] autorelease] in thing, but this has an important purpose. (A special purpose, if you will, which you’ll want to use every chance you get.) Simply returning _thing in thing does not suffice, as the following code demonstrates.

1 id something = [myObject thing];
2 [myObject setThing:nil]; // Clear out the thing.
3 [something doSomething];

In line 3, your app will go boom. I’ve seen it argued (on bathroom stalls, for example) that the caller ought to [[myObject thing] retain] on line 1 because of this possibility, but that’s simply not the caller’s responsibility. It’s an implementation detail of myObject that thing returns an instancvariabl which setThing: releases. Moreover, the caller could inadvertently call setThing: by calling some other method that calls setThing: rather than by calling setThing: directly. With [[_thing retain] autorelease], thing ensures that _thing will not be deallocated in the caller’s scope (as long as the caller doesn’t do anything stupid, like call out Minnesota Fats).

No discussion of accessors is complete without talking about thread safety. In order to write thread-safe accessors, you should first drink a bottle of whiskey. This is required because writing thread-safe accessors is a fool’s errand. Don’t do it. Don’t try it. Don’t even think about. Redesign your code to avoid the need for thread-safe accessors. If you feel you must, however, then you should acquaint yourself with Technical Note TN2123, because you’ll find yourself referring to it frequently. It’ll be like a nightmare, just getting (and setting) worse and worse. But at least the salad dressing will be good.

Postlude in C4[2] major

September 8th, 2008

I’m back safe, cat in lap, from C4[2]. This year’s theme was “Don’t ship until it’s ready, i.e., early and often, and don’t price too low, i.e., make it free.” I would like to thank @rentzsch for hosting the best conference I’ve ever attended (with the possible exception of the Marty Feldman fan club). I’d also like to suggest that C4[3] be moved to neighboring Wisconsin, which is home to @rentzsch as well as to “Fun”, as @dylanbr (or was it @bruzenak?) correctly noted.

The highlight of the weekend was meeting a lot of people — basically, everyone, including my coworkers — for the first time. Unfortunately, however, they came to realize that I’m a complete fraud who has been contracting out all of my coding to @macgeek02. As a result, I was fired by @PBones, fired by qdc (@???), and retroactively fired by @markonen. Fortunately, I had a backup plan: I stowed away in @wilshipley’s luggage and am now living in his basement.

C4[2] was not brought to you by the letter ‘w’. For some strange reason, the Apple Store refuses to sell individual keycaps. Disaster was avoided, though, when @PBones genius-ly performed an emergency transplant. |hat a relief that \as!

backslash key w key

Another disaster was avoided when I failed to get into a fight. There were many opportunities. The much anticipated battle for supremacy over Radioshift between myself and @kickingbear never materialized. A little anticipated battle over tunes was quickly resolved when @mikeash chose Dire Straits. Apparently, drunkenbatman was too afraid to show after hearing about my unresolved anger over crashing our WebKit apps. On the other hand, the unresolved anger of @jimcorreia over stealing his chair was redirected toward @chockenberry.

I was pleasantly surprised to learn that someone other than my cat and my parole officer reads my blog. I won’t name names, for the same reason that “Hustler” comes in a plain, brown wrapper. I won’t name everyone I met at C4 either, because there are [2] many, but please know that I enjoyed talking with you and that I’ve put all of your names in an SQLite database, of course.

Cocoa memory management for smarties, Part 2: working with a nib

August 25th, 2008

Well, it’s back to work for the moment. I was offered the VP slot, but I had to turn it down because they refused to accept the NDA: my name would be on the ticket, but nobody could talk about me publicly. Also, they wouldn’t get rid of the brown M&Ms. I am waiting for an offer by email from another guy, but I don’t hold out much hope, since I’m also waiting for him to learn how to use email.

In part 1 of this series I talked about Cocoa memory management. For a summary of that post, load it in your browser, select all, and pass it to the Summarize system service. And now for something completely the same, in part 2 I’m going to talk about Cocoa memory management. As you all know, I love nibs. I find them to be a very human-friendly interface, much like the gom jabbar. A nib file contains archived Objective-C objects that are instantiated when the nib is instantiated, so their memory needs to be managed just as objects instantiated programmatically. Fortunately, if the nib File’s Owner is an NSWindowController or (new in Leopard) NSViewController, the File’s Owner takes care of the memory management automatically. Otherwise, it’s your job.

According to the documentation, Objects in a nib file are initially created with a retain count of 1. As it rebuilds the object hierarchy, however, Cocoa autoreleases any objects that have a parent or owning object, such as views nested inside view hierarchies. By the time the nib-loading code is complete, only the top-level objects in the nib file have a positive retain count and no owning object. This makes the top-level objects a potential memory leak if your code does not assume responsibility for them. If you look at your nib with the icon view in Interface Builder, the top-level objects consist of everything except the proxy objects such as File’s Owner, First Responder, and (new in Leopard) Application. Thus, top-level objects include not only windows but also contextual menus, array controllers, etc. For example, Vienna’s MainMenu.nib, pictured below, contains 14 top-level objects. (Kids, don’t try this at home.)

MainMenu.nib

By the way, the MainMenu.nib file, or whatever is specified by NSMainNibFile in Info.plist, is actually a special case, because the File’s Owner is NSApplication (or whatever is specified by NSPrincipalClass). You don’t need to worry about its memory management either, although the objects in the nib will usually remain in memory for the lifetime of the app. On termination, NSApplication may or may not choose to release those objects, as it pleases, so don’t depend on any code in dealloc. Cleaning up memory on app termination is like sweeping your floor right before a tornado hits.

In order to manage the memory of the nib’s top-level objects, you’ll need a reference to them. The method -[NSNib instantiateNibWithOwner: topLevelObjects:] is handy in this respect. The documentation of the (NSArray **) topLevelObjects argument may be a little confusing, though: On input, a variable capable of holding an NSArray object. On output, this variable contains an autoreleased NSArray object containing the top-level objects from the nib file. Although the NSArray is autoreleased, the top-level objects themselves are not. Each object in the NSArray will have a retain count of at least 2. Thus, after the NSArray is deallocated and releases its objects, they will each still have a retain count of at least 1. A typical way to handle this is as follows.


@interface MyObject : NSObject
{ NSArray * _topLevelObjects; }
@end

@implementation MyObject

-(id) init
{
	self = [super init];
	if (self)
	{
		NSNib * nib = [[[NSNib alloc] initWithNibNamed:@"MyNib" bundle:nil] autorelease];
		if (nib && [nib instantiateNibWithOwner:self topLevelObjects:&_topLevelObjects])
		{
			// The array is autoreleased, so we need to retain it.
			// Release the objects now so that they'll be deallocated along with the array.
			[[_topLevelObjects retain] makeObjectsPerformSelector:@selector(release)];
		}
	}
	return self;
}

-(void) dealloc
{
	[_topLevelObjects release];
	[super dealloc];
}

@end

If you use a different method to instantiate the nib, such as +[NSBundle loadNibNamed:owner:], or if you don’t want to keep an array of the top-level objects, you’ll need to create an IBOutlet for each top-level object in the nib and release the objects in dealloc along with any other ivars.

A major caveat for do-it-yourself nib loading is that even if you take care to release your top-level objects, you can still get a memory leak if you use Cocoa bindings in your nib. This occurs when an object in the nib binds to the File’s Owner. The File’s Owner never gets deallocated in this case, and thus neither do the top-level objects. Again, NSWindowController and NSViewController already take care of this problem automatically, but you’ll need to deal with it if the File’s Owner is not one of those classes or their subclasses. Basically, there are three possible solutions:

  1. Unbind the bindings programmatically. You’ll need to do this elsewhere than the File Owner’s dealloc, which won’t get called unless you unbind.
  2. Bind to a different object in the nib rather than to the File’s Owner.
  3. Don’t use Cocoa bindings and nibs, because they’re teh suck.

Slow news day: favorite feeds updated

August 5th, 2008

It’s been a while since I’ve updated my Favorite Feeds in the Downloads section of the sidebar of my blog front page. (Sounds like AppleScript, eh?) I would export from Vienna and update it every day, but I have to manually edit the .opml file first to remove embarrassing subscriptions such as porn and the New York Times. For your convenience and amusement, the latest version is up now.