Cocoa / Objective-C从posix路径(path / to / desktop)获取HFS路径(path:to:desktop) [英] Cocoa/Objective-C get a HFS path (path:to:desktop) from a posix path (path/to/desktop)

查看:148
本文介绍了Cocoa / Objective-C从posix路径(path / to / desktop)获取HFS路径(path:to:desktop)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在OSX,Objective-C上。

I am on OSX, Objective-C.

我有一个路径/ NSURL,例如

I have a path/NSURL like

/Users/xxx/Desktop/image2.png

但是我通过了到希望使用查找程序路径的第三方应用程序中

But i pass it to a third party application that excpects finder pathes like

Harddisk:Users:Desktop:image2.png

是否有任何方法(我找不到)来转换这样的路径或将其从NSURL中删除(如果可能的话,

Is there any method (i can't find) to convert pathes like that or get them out of an NSURL (if possible without string modifying)?

在AppleScript中是

In AppleScript it is

return POSIX file "/Users/xxx/Desktop/image2.png" -->  Harddisk:Users:xxx:Desktop:image2.png

EDIT :此几乎相同:可可路径字符串转换
不幸的是,该方法已被弃用...

EDIT: This is pretty much the same: Cocoa path string conversion Unfortunately, the method is deprecated...

推荐答案

目前没有(简便)替代方案。

There is no (easy) alternative at the moment.

不推荐使用功能 CFURLCopyFileSystemPath ,仅推荐枚举类型 kCFURLHFSPathStyle ,而原始值 1 仍在工作,并且避免了警告。

The function CFURLCopyFileSystemPath is not deprecated, only the enum case kCFURLHFSPathStyle is deprecated but the raw value 1 is still working and avoids the warning.

我正在使用 NSString

@implementation NSString (POSIX_HFS)

- (NSString *)hfsPathFromPOSIXPath
{
    CFStringRef hfsPath = CFURLCopyFileSystemPath((CFURLRef)[NSURL fileURLWithPath:self], 1);
    return (NSString *)CFBridgingRelease(hfsPath);
}
@end

该功能在Swift中也有效。 Swift版本稍微复杂一些,并隐式地添加了表示字典的尾部分号,这里是 URL 的扩展名:

The function works also in Swift. The Swift version is a bit more sophisticated and adds the trailing semicolon representing a dictionary implicitly, here as an extension of URL:

extension URL {

  func hfsPath() -> String?
  {
    if let cfpathHFS = CFURLCopyFileSystemPath(self as CFURL, CFURLPathStyle(rawValue: 1)!) { // CFURLPathStyle.CFURLHFSPathStyle)
      let pathHFS = cfpathHFS as String
      do {
        let info = try self.resourceValues(forKeys: [.isDirectoryKey, .isPackageKey])
        let isDirectory = info.isDirectory!
        let isPackage =  info.isPackage!

        if isDirectory && !isPackage {
          return pathHFS + ":" // directory, not package
        }
      } catch _ {}
      return pathHFS
    }
    return nil
  }
}

这篇关于Cocoa / Objective-C从posix路径(path / to / desktop)获取HFS路径(path:to:desktop)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆