如何获取 Cocoa/Obj-C 中两个或多个文件的共同祖先目录?
我有一堆文件,要么是 NSString 要么是 NSURL(没关系;它们在大多数情况下是可以互换的),我需要一种方法找到共同祖先目录。有谁知道该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可以发誓某处有一个
pathByJoiningPathComponents
方法,或者至少有一个类似的方法,但我一定在想别的东西。这对路径有用,如果你使用的是 10.6,它也可能适用于 URL(我只用路径测试过):不幸的是,我认为没有“内置”方法可以做到这一点。
如果您有一个要查找共同祖先的文件路径数组,您可以执行以下操作:
如果您想保持自动释放池干净,您可能需要显式分配和释放其中一些对象,特别是如果您有一大堆路径。
I could have sworn there was a
pathByJoiningPathComponents
method somewhere, or at least one like it, but I must be thinking of something else. This does the trick for paths, it may work for URLs too if you're on 10.6 (I only tested it with paths):I don't think there is a “built-in” way to do it, unfortunately.
If you have an array of file paths that you want to find the common ancestor, you could do something like this:
You may want to explicitly allocate and release some of these objects if you want to keep the autorelease pool clean, especially if you have a large array of paths.
将路径表示为组件的 NSArray。 (在 Mac OS X 10.6 及更高版本中,向每个对象发送
pathComponents
消息;在早期版本和 iPhone 操作系统中,您需要向 NSURL 对象发送path
消息获取 NSStrings,然后发送pathComponents
消息。)拥有一个包含到目前为止公共路径的 NSMutableArray。将其初始化为第一个路径的组件。
对于每个后续路径,使用 NSEnumerator 同步迭代该路径和当前路径。
完成后,您将拥有零个或多个路径组件的数组。将这些连接到绝对路径字符串中将生成公共路径字符串。
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 objectspath
messages to get NSStrings, then send those thepathComponents
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.
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.
获取一个文件,获取下一个文件,迭代其祖先(NSString 的
pathComponents
方法对此很有用),直到找到它们的共同点。然后转到下一个文件,看看它是否具有相同的祖先。如果没有,请继续回溯,直到找到他们的共同点。不断重复此操作,直到到达列表的末尾。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.