【问题标题】:Correct way to get Application directory path in Mac App在 Mac App 中获取应用程序目录路径的正确方法
【发布时间】:2017-05-06 02:29:41
【问题描述】:

从我的 Mac OS 应用程序中,我尝试使用以下代码获取应用程序的当前目录,以便在应用程序包路径中生成日志文件。

NSString *path = [[[NSFileManager defaultManager] currentDirectoryPath] stringByAppendingPathComponent:@"TSPlogfile.txt"];

当我从 Xcode 运行应用程序时它运行良好,但发现 [[NSFileManager defaultManager] currentDirectoryPath] 在从 finder 运行 applicationxxx.app 时只返回 /

后来我用[[[NSBundle mainBundle].bundlePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"TSPlogfile.txt"];解决了这个问题

这在两种情况下都可以正常工作(从 Xcode 和 finder 运行应用程序)

你能解释一下为什么[[NSFileManager defaultManager] currentDirectoryPath] 在从 finder 运行应用程序时会失败吗?

【问题讨论】:

    标签: objective-c nsfilemanager nsbundle


    【解决方案1】:

    您不应向应用程序所在的捆绑包或文件夹中写入任何内容。如果您的应用是sandboxed,您将无法使用。

    改用“应用程序支持”文件夹:

    NSError *error;
    NSFileManager *manager = [NSFileManager defaultManager];
    NSURL *applicationSupport = [manager URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:&error];
    NSString *identifier = [[NSBundle mainBundle] bundleIdentifier];
    NSURL *folder = [applicationSupport URLByAppendingPathComponent:identifier];
    [manager createDirectoryAtURL:folder withIntermediateDirectories:true attributes:nil error:&error];
    NSURL *fileURL = [folder URLByAppendingPathComponent:@"TSPlogfile.txt"];
    

    我在上面使用了NSURL 实现,但是如果使用路径,同样的概念也适用。

    File System Programming Guide: macOS Library Directory Details

    你问:

    你能解释一下为什么[[NSFileManager defaultManager] currentDirectoryPath] 在从 finder 运行应用程序时会失败吗?

    您碰巧在 Finder 中查看的文件夹与应用程序运行时的“当前目录”不同。总之,“当前目录”与应用所在的位置无关。

    【讨论】:

      【解决方案2】:

      这是获取应用包所在目录的方法:

      NSURL *appFolder = [[[NSBundle mainBundle] bundleURL] URLByDeletingLastPathComponent];
      

      这为您提供了应用程序文件夹(/Applications 和 ~/Applications)的路径

      NSArray *paths =[[NSFileManager defaultManager] URLsForDirectory:NSApplicationDirectory inDomains:NSLocalDomainMask];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-30
        • 1970-01-01
        • 1970-01-01
        • 2012-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-19
        相关资源
        最近更新 更多