简体   繁体   English

Mac 沙盒和临时文件

[英]Mac Sandboxing and Temp files

I'm working on sandboxing my applications and I've got a problem because a library that I use creates temporary files when it modifies the original file, eg我正在对我的应用程序进行沙盒处理,但我遇到了一个问题,因为我使用的库在修改原始文件时会创建临时文件,例如

When it changes something in "Hello World.txt" it will create a "Hello World_temp.txt" file in the same directory and then when it's finished it will swap both files.当它更改“Hello World.txt”中的某些内容时,它将在同一目录中创建一个“Hello World_temp.txt”文件,然后当它完成时将交换两个文件。

This of course breaks sandboxing rules because you are only allowed to change the source file and not go around creating other files in the folder.这当然打破了沙盒规则,因为您只能更改源文件,而不能在文件夹中创建其他文件。

I can't find any recommendations about what to do with temp files, so I'm currently just going to create the temp file in the application's container where I'm allowed to write and then swap the files.. however, that's not great if the application and the file are on different disks as it will involve copying rather than moving.我找不到关于如何处理临时文件的任何建议,所以我目前只想在应用程序的容器中创建临时文件,我可以在其中写入然后交换文件..但是,这不是很好如果应用程序和文件在不同的磁盘上,因为这将涉及复制而不是移动。

Is there a place for temporary files that we're allowed to write to?是否有允许我们写入临时文件的地方?

Best regards,此致,

Frank坦率

On 10.7.3+ (also works out of the sandbox on 10.6) try the NSFileManager method URLForDirectory:inDomain:appropriateForURL:create:error: (docs) .在 10.7.3+(也可以在 10.6 的沙箱外运行)尝试NSFileManager方法URLForDirectory:inDomain:appropriateForURL:create:error: (docs) This should give you a temporary directory on a particular volume.这应该为您提供特定卷上的临时目录。 Once created you can use replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: to switch the files.创建后,您可以使用replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:来切换文件。

Now some uncertainty:现在有些不确定:

On 10.7 -> 10.7.2 the above method may not work in the sandbox.在 10.7 -> 10.7.2 上,上述方法在沙箱中可能不起作用。 Instead you can use the function NSTemporaryDirectory() (docs) .相反,您可以使用函数NSTemporaryDirectory() (docs) You may find that replaceItemAtUrl... also does not work in this case when under the sandbox, in which case write your own code to read/write the temporary back.可能会发现,在沙箱下的这种情况下, replaceItemAtUrl...也不起作用,在这种情况下,请编写您自己的代码来读/写临时文件。

NSTemporaryDirectory() works in sandbox. NSTemporaryDirectory()在沙箱中工作。 Sample code in Swift: Swift 中的示例代码:

let path = "\(NSTemporaryDirectory())temp.txt"
"Hello world".writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM