views:

91

answers:

3

I have a bunch of files, either NSStrings or NSURLs (it doesn't matter; they are, for the most part, interchangeable), and I need a way to find the common ancestor directory. Does anyone know how to do this?

+1  A: 

Take a file, take the next file, iterate through its ancestors (NSString's pathComponents method will be useful for this) until you find one that they have in common. Then move onto the next file, see if it has the same ancestor. If not, keep going back until you find one they do have in common. Keep repeating this until you reach the end of the list.

Chuck
+2  A: 

Represent the paths as NSArrays of components. (In Mac OS X 10.6 and later, send each object a pathComponents message; in earlier versions and on the iPhone OS, you'll need to send NSURL objects path messages to get NSStrings, then send those the pathComponents messages.)

Have an NSMutableArray containing the common path so far. Initialize it to the first path's components.

For each subsequent path, iterate both that path and the current path so far in lockstep using NSEnumerators.

  • If the common path so far runs out, no change.
  • If the path you're examining runs out, it is the new common path.
  • If you encounter an inequal component, all components before it are the new common path. Break the lockstep iteration here.

When you finish, you'll have an array of zero or more path components. Joining these into an absolute path string will produce the common path string.

Peter Hosey
+2  A: 
dreamlax
Wow! This is great! How could I do this, though, with more than two file paths? (Please vote up this question. I used up my rep. on bounties. Thx.)
Alexsander Akers
I have updated my answer. It's not pretty, but it'll give you an idea on what needs to be done. This is O(n^2) as far as I can tell too. There is probably a more optimal solution.
dreamlax
NSString has a `pathWithComponents:` class method.
Peter Hosey