Searching the Macintosh File System

Every now and then, an application needs to search the user's hard disk to find files.  Here are four ways to do it:

NSWorkspace.  NSWorkspace has various methods which are very easy to use but they only search in "known" places for things like apps.  Also, if there is more than installation of an app on a system, it only returns one result, and the next time you run it, it may or may not return a different result.  Use NSWorkspace if you can live with these limitations.

Unix find command.  Comprehensive search, but way too slow for most applications and also requires NSTask to launch a separate process, which is going to have reliability issues when thousands of people start using your app.  There are lots of find tutorials on the internet.

Programmatic Spotlight search (NSMetadataQuery).  The fastest method, typically searches in a few seconds.  But it may miss items because it does not search inside packages, and also will not search any items that the user has marked to not search in Spotlight Preferences.  There may be other exclusions that I am not aware of.  (I learned the first limitation the hard way, still can't find any documentation of it.)  Not too difficult to write code, but even easier if you download SSYFileFinder class.  SSYFileFinder is written to find files by name but could be easily modified to do other searches.  Comes with HeaderDoc documentation.

The Carbon File Manager (PBCatalogSearchSync/PBCatalogAsync).  Not as fast as Spotlight, usually 2-3x slower, but does not miss the items that Spotlight misses.  I use this method in Bookmarksman to find the full paths of any Bookwatchdog packages.  (Bookwatchdogs are inside Bookdog packages, and full paths are needed in order to programatically remove them from Login Items.  Thanks Apple for not endowing Login Items with the same ambiguity identifying applications that confuses AppleScript, NSWorkspace and Launch Services.)  Anyhow, coding and debugging for the File Manager, malloccing structs inside of structs inside of parameter blocks, however, can eat up the better part of a week.  To get a head start, look at SSYCarbonSearcher.  SSYCarbonSearcher is also written to find files by name, but could be modified to do other searches, thanks to Inside Macintosh documentation now being built into Xcode.  Just ⌘-doubleclick on a symbol like FSCatalogInfo and blast off into the past!  SSYCarbonSearcher, and comes in a project that also includes a demo command-line tool and a demo Cocoa app, and the reuseable class has HeaderDoc documentation.  


REPOSITORY

Visit this project's GitHub Repository to download, fetch, or clone this code.