获取 Cocoa 中的相对路径
我想获得可可应用程序中的相对路径。
前任。
- 输入:/Users/foo/bar/sample.txt
- 基本路径:/Users/foo
- 预期输出:bar/sample.txt
我怎样才能得到这个?
I would like to get relative path in cocoa app.
ex.
- Input: /Users/foo/bar/sample.txt
- Base path: /Users/foo
- Expected output: bar/sample.txt
How can I get this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看 GitHub 上的开源 KSFileUtilities 类。
我知道它们使用 URL,但大多数 API 现在建议使用基于 NSURL 的文件路径。
即便如此,也有一些获取相对路径的方法。
Have a look at the Open Source KSFileUtilities classes on GitHub.
I know they work with URLs, but most APIs recommend using NSURL based file paths now.
Even so, there are some methods for getting relative paths as well.
似乎没有内置的方法可以做到这一点。下面是 Swift 中的一个简单示例,可能对某些人有用,但请记住,有许多例外情况需要规则,因此最好使用 KSFileUtilities,它看起来不错。
There appears to be no built in way of doing this. A quick example in Swift which could be useful for some people is below, but bear in mind there are many exceptions to rule, so it would probably be better to go with the KSFileUtilities, which looks good.
如果您正在谈论相对路径到基本路径,您可以尝试 NSString 类中的 ComponentsSeparatedByString 方法。它返回一个数组。
例如,如果您有 /User/boo/bar/sample.txt 的 NSString * 输入,并且通过以下方式调用该方法:
[input ComponentsSeparatedByString:@"/"]
,您将得到一个包含 4 个元素的数组。元素 0 = User、元素 1 = boo、元素 2 = bar 和元素 3 = sample.txt。从那里,您可以与基本路径进行比较,仅获取剩余路径,并使用 NSString 类中的 stringByAppendingPathComponent 方法将它们追加回来。
If you are talking about relative path the to base path, you can try the componentsSeparatedByString method in the NSString class. It returns an array.
for example, if you have a NSString * input of /User/boo/bar/sample.txt and you call the method by:
[input componentsSeparatedByString:@"/"]
, you'll get an array of 4. Element 0 = User, element 1 = boo, element 2 = bar and element 3 = sample.txt.From there you do comparisons with your base path and take only the remaining and append them back using stringByAppendingPathComponent method in NSString class.