An NSURL Category For Adding to Favorites Lists

I encountered a question on StackOverflow today about how to add items to the favorites list in the Finder sidebar (which also appears in the standard Open and Save dialogs’ side bars). Though it’s already been answered before (I marked it as a duplicate, pointing to an answer from 2011), it appears the information is a bit outdated and contained no example code. I wrote, tested, and added the code to an updated answer. Not satisfied to stop there, I felt it would be easier to use if I created a simple category on NSURL so you could tell a valid file URL directly to add itself to either the favorite items or favorite volumes list with one call. It’s compatible back to 10.5.

I wanted the design and usage to be simple, so I made a few drastic decisions:

  1. Due to some Finder bugs, you could set either a custom icon or a custom title for an item, but not both at the same time. Since the default behavior is to use the default icon and file name (sans extension, if one exists), I simply don’t provide the option to customize the icon or name.
  2. Though there’s an option to specify adding an item to the end, or to the beginning, or even to resolve each item and specify an item after which to add your own, this complicates matters, so I opted for append only. Your users may not appreciate you putting your item at the top of their lists anyway. Back of the line, new guy. 😉
  3. The call either succeeds or fails. No complicated error messages, no nothing.
  4. Any valid file URL can be added by calling either [url appendToFavoriteItemsList]; or [url appendToFavoriteVolumesList]; and checking the BOOL return value if you care.

The Code


#import "NSURL+FavoritesList.h
NSString * itemPath = [@"~/Music" stringByExpandingTildeInPath];
NSURL * itemURL = [NSURL fileURLWithPath:itemPath];
[itemURL appendToFavoriteItemsList];

I hope you find it useful!

Related Posts