获取Cocoa中的相对路径

获取Cocoa中的相对路径,cocoa,relative-path,Cocoa,Relative Path,我想在cocoa应用程序中获取相对路径 前 输入:/Users/foo/bar/sample.txt 基本路径:/Users/foo 预期输出:bar/sample.txt 我怎样才能得到这个呢?看看GitHub上的开源类 我知道它们使用URL,但大多数API建议现在使用基于NSURL的文件路径 即使如此,也有一些方法可以获取相对路径。如果您讨论的是到基本路径的相对路径,您可以尝试NSString类中的componentsSeparatedByString方法。它返回一个数组 例如,如果您有一个

我想在cocoa应用程序中获取相对路径

输入:/Users/foo/bar/sample.txt 基本路径:/Users/foo 预期输出:bar/sample.txt
我怎样才能得到这个呢?

看看GitHub上的开源类

我知道它们使用URL,但大多数API建议现在使用基于NSURL的文件路径


即使如此,也有一些方法可以获取相对路径。

如果您讨论的是到基本路径的相对路径,您可以尝试NSString类中的componentsSeparatedByString方法。它返回一个数组

例如,如果您有一个NSString*输入/User/boo/bar/sample.txt,并通过以下方式调用该方法: [InputComponentsSeparatedByString:@/],您将得到一个4的数组。元素0=User,元素1=boo,元素2=bar,元素3=sample.txt


从这里开始,您可以与基本路径进行比较,并仅获取剩余路径,然后使用NSString类中的stringByAppendingPathComponent方法将它们追加回来。

似乎没有内置的方法来完成此操作。下面是Swift中一个可能对某些人有用的快速示例,但请记住该规则有许多例外,所以最好使用KSFileUtilities,它看起来不错

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
}

谢谢你的回复,但是OSX中没有默认的内置api吗?相对于什么?用户输入基本路径、主文件夹或其他内容?我认为实现这一点的唯一方法是比较两个URL对象的pathComponents。如果其中一个是另一个的前缀,则可以检查其中一个。但是,没有用于此的内置API。请不要这样做。改为使用-[NSString pathComponents]。不能保证/是路径组件分隔符。@lemnar它在OS X上或多或少是有保证的,并且没有多少人会为其他平台用Objective-C编写任何东西。真正的原因是文件/文件夹名中可能包含/。