【问题标题】:How do I get the default temporary directory on Mac OS X?如何获取 Mac OS X 上的默认临时目录?
【发布时间】:2010-09-27 07:53:26
【问题描述】:

我想为一些单元测试创​​建一些数据目录,并且我希望这些目录位于用户的默认临时目录中。

我想我可以在 /tmp 下创建一个子目录,但我不想假设有人如何设置自己的机器。

我打算即时编写测试数据,这就是为什么我想把它放到一个临时目录中。

【问题讨论】:

  • 另请注意,在运行沙盒的进程中无法访问 /tmp(使用普通沙盒规则,如通过 Mac App Store 分发的内容)

标签: objective-c macos cocoa test-data temporary-directory


【解决方案1】:

不要使用tmpnam()tempnam()。它们是不安全的(有关详细信息,请参阅man page)。不要假设/tmp。将NSTemporaryDirectory()mkdtemp() 结合使用。 NSTemporaryDirectory() 会给你一个更好的使用目录,但是它可以返回nil。我使用过类似这样的代码:

NSString * tempDir = NSTemporaryDirectory();
if (tempDir == nil)
    tempDir = @"/tmp";

NSString * template = [tempDir stringByAppendingPathComponent: @"temp.XXXXXX"];
NSLog(@"Template: %@", template);
const char * fsTemplate = [template fileSystemRepresentation];
NSMutableData * bufferData = [NSMutableData dataWithBytes: fsTemplate
                                                   length: strlen(fsTemplate)+1];
char * buffer = [bufferData mutableBytes];
NSLog(@"FS Template: %s", buffer);
char * result = mkdtemp(buffer);
NSString * temporaryDirectory = [[NSFileManager defaultManager]
        stringWithFileSystemRepresentation: buffer
                                    length: strlen(buffer)];

您现在可以在temporaryDirectory 中创建文件。删除生产代码的NSLogs

【讨论】:

    【解决方案2】:

    回顾那里的这个问题和 NSTemporaryDirectory() 的文档,如果您使用的是 10.6 或更高版本,那么建议您使用 NSFileManager 中的URLForDirectory:inDomain:appropriateForURL:create:error: 方法,以获得更灵活的创建目录的方法。

    它返回一个 URL 而不是字符串路径,这是我们推荐使用的另一件事。

    【讨论】:

    • 您如何以及在何处获取临时目录。似乎有一些 api issuesNSItemReplacementDirectory。 NSHipster published实际上,这种方法似乎是为了将现有的临时文件移动到磁盘上的永久位置,-replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:.
    【解决方案3】:

    在 Objective-C 中你可以使用 NSTemporaryDirectory()。

    【讨论】:

      【解决方案4】:

      【讨论】:

      • tempnam() 和 tmpnam() 不安全。请改用 mkstemp()。
      • 也许不是,但至少我发现了 TEMPDIR
      猜你喜欢
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2011-11-09
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      相关资源
      最近更新 更多