I have a bunch of files, either NSString
s or NSURL
s (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?
views:
91answers:
3Take 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.
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.