在Mac App中获取应用程序目录路径的正确方法

时间:2016-12-20 19:17:54

标签: objective-c nsfilemanager nsbundle

在我的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运行应用程序时失败了吗?

2 个答案:

答案 0 :(得分:5)

您不应该向软件包或应用程序所在的文件夹写任何内容。如果您的应用是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: OS X Library Directory Details

你问:

  

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

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

答案 1 :(得分:1)

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

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

这为您提供了Application文件夹(/ Applications和〜/ Applications)的路径

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