Vincent Gable’s Blog

June 2, 2010

NSHomeDirectory() is a Bad Thing

Filed under: Announcement,Cocoa,iPhone,MacOSX,Objective-C,Programming | , ,
― Vincent Gable on June 2, 2010

Code that uses NSHomeDirectory() is probably doing The Wrong Thing. It’s not appropriate to clutter up the user’s home directory — internal application-data should be stored in the Application Support directory (or a temporary file if it’s transient). So I can’t think of a good reason to get the path to the user’s home directory. Every use of NSHomeDirectory() I’ve seen is spamming the home directory, or getting a subdirectory in a brittle way.

For sample code that gets a directory robustly, using NSSearchPathForDirectoriesInDomains(), see Finding or creating the application support directory.

Because NSHomeDirectory() encourages so many bad practices, it should be deprecated.

Disabling NSHomeDirectory() in Your Projects

Add the following macro to your prefix file:

#define NSHomeDirectory() NSHomeDirectory_IS_DISCOURAGED_USE_NSSearchPathForDirectoriesInDomains_TO_GET_A_SUBDIRECTORY_OF_HOME

Then any use of NSHomeDirectory() will give the compiler error:

error:
‘NSHomeDirectory_IS_DISCOURAGED_USE_NSSearchPathForDirectoriesInDomains_TO_GET_A_SUBDIRECTORY_OF_HOME’ undeclared (first use in this function)

Tell Me I’m Wrong

If you’ve seen a legitimate use of NSHomeDirectory() please leave a comment! Just because I can’t think of one doesn’t mean they don’t exist.

3 Comments »

  1. I agree with this advice in general. However, the one legitimate case I can think of is to interoperate with existing unixy utilities that store files under the user’s home directory. That is, those files and directories that typically begin with a dot, for instance .ssh, .m2, .subversion.

    I don’t disagree that this more or less amounts to spamming the home directory, but it is pretty standard in the unix world. That being said, I was surprised to notice that my home folder contains a .dropbox directory – I would’ve expected them to use Application Support.

    Comment by Greg Wiseman — June 2, 2010 @ 2:07 pm

  2. Good point Greg! I have 27 files starting with a dot in my home directory, and I use “GUI” frontends for some of the UNIX tools that spawned them. I haven’t looked at the source for those front-ends, but it makes sense that some of them need to poke around in ~.

    That said, I still wish NSHomeDirectory() would go away, leaving the unixy tools to use unixy-calls to “spam” the home directory; because I’d rather have the Foundation API’s optimized for the general case of building “native” apps, not ports and wrappers of UNIX tools. After all, accourding to Apple’s diagram, Foundation and Cocoa live pretty far “above” the UNIX layer.

    Comment by Vincent Gable — June 2, 2010 @ 4:39 pm

  3. Here’s a legitimate use: in iOS. :)

    Comment by Duncan Babbage — October 30, 2011 @ 12:48 am

RSS feed for comments on this post.

Leave a comment

Powered by WordPress