开发者

Get Relative Path in Cocoa

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 ge开发者_如何学Pythont this?


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.


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.

func relativePath(absolutePath : String, basePath : String) -> String {
    var absolutePathComponents = absolutePath.pathComponents
    var basePathComponents = basePath.pathComponents

    if absolutePathComponents.count < basePathComponents.count {
       return absolutePath
    }

    var levelIndex = 0 //number of basePath components in absolute path

    for (index, baseComponent) in enumerate(basePathComponents) {

        if (baseComponent != absolutePathComponents[index]) {
            break
        }
        levelIndex++
    }

    if levelIndex == 0 {
         return absolutePath
    }

    var relativePath : String = ""


    if levelIndex < basePathComponents.count {
        //outside of base path
        for (var index = levelIndex; index < basePathComponents.count; index++) {
            relativePath = relativePath.stringByAppendingPathComponent("../")
        }
    }


    for(var index = levelIndex; index < absolutePathComponents.count; index++) {
        relativePath = relativePath.stringByAppendingPathComponent(absolutePathComponents[index])
    }

    return relativePath
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜