objective-c 如何使用 Cocoa 创建临时文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/215820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:51:36  来源:igfitidea点击:

How do I create a temporary file with Cocoa?

objective-ccocoafile-io

提问by lfalin

Years ago when I was working with C# I could easily create a temporary file and get its name with this function:

多年前,当我使用 C# 时,我可以轻松地创建一个临时文件并使用此函数获取其名称:

Path.GetTempFileName();

This function would create a file with a unique name in the temporary directory and return the full path to that file.

此函数将在临时目录中创建一个具有唯一名称的文件,并返回该文件的完整路径。

In the Cocoa API's, the closest thing I can find is:

在 Cocoa API 中,我能找到的最接近的是:

NSTemporaryDirectory

Am I missing something obvious or is there no built in way to do this?

我是否遗漏了一些明显的东西,或者没有内置的方法来做到这一点?

采纳答案by lfalin

A safe way is to use mkstemp(3).

一种安全的方法是使用mkstemp(3)

回答by Ben Gottlieb

[Note: This applies to the iPhone SDK, not the Mac OS SDK]

[注意:这适用于 iPhone SDK,不适用于 Mac OS SDK]

From what I can tell, these functions aren't present in the SDK (the unistd.hfile is drastically pared down when compared to the standard Mac OS X 10.5 file). I would use something along the lines of:

据我所知,这些功能不存在于 SDK 中(unistd.h与标准 Mac OS X 10.5 文件相比,该文件被大幅缩减)。我会使用以下内容:

[NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @"txt"]];

Not the prettiest, but functional

不是最漂亮,但功能强大

回答by muzz

Apple has provided an excellent way for accessing temp directory and creating unique names for the temp files.

Apple 提供了一种极好的方法来访问临时目录并为临时文件创建唯一名称。

- (NSString *)pathForTemporaryFileWithPrefix:(NSString *)prefix
{
    NSString *  result;
    CFUUIDRef   uuid;
    CFStringRef uuidStr;

    uuid = CFUUIDCreate(NULL);
    assert(uuid != NULL);

    uuidStr = CFUUIDCreateString(NULL, uuid);
    assert(uuidStr != NULL);

    result = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%@", prefix, uuidStr]];
    assert(result != nil);

    CFRelease(uuidStr);
    CFRelease(uuid);

    return result;
}

LINK :::: http://developer.apple.com/library/ios/#samplecode/SimpleURLConnections/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009245see file :::AppDelegate.m

链接 :::: http://developer.apple.com/library/ios/#samplecode/SimpleURLConnections/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009245见文件 :::AppDelegate.m

回答by Quinn Taylor

Though it's nearly a year later, I figured it's still helpful to mention a blog post from Cocoa With Love by Matt Gallagher. http://cocoawithlove.com/2009/07/temporary-files-and-folders-in-cocoa.htmlHe shows how to use mkstemp()for files and mkdtemp()for directories, complete with NSString conversions.

尽管已经过去了将近一年,但我认为提及 Matt Gallagher 撰写的 Cocoa With Love 的博客文章仍然很有帮助。http://cocoawithlove.com/2009/07/temporary-files-and-folders-in-cocoa.html他展示了如何使用mkstemp()文件和mkdtemp()目录,完成 NSString 转换。

回答by Philipp

I created a pure Cocoa solution by way of a category on NSFileManagerthat uses a combination of NSTemporary()and a globally unique ID.

我通过NSFileManager使用NSTemporary()和 全局唯一 ID的组合创建了一个纯 Cocoa 解决方案。

Here the header file:

这里的头文件:

@interface NSFileManager (TemporaryDirectory)

-(NSString *) createTemporaryDirectory;

@end

And the implementation file:

和实现文件:

@implementation NSFileManager (TemporaryDirectory)

-(NSString *) createTemporaryDirectory {
 // Create a unique directory in the system temporary directory
 NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];
 NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:guid];
 if (![self createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil]) {
  return nil;
 }
 return path;
}

@end

This creates a temporary directory but could be easily adapted to use createFileAtPath:contents:attributes:instead of createDirectoryAtPath:to create a file instead.

这会创建一个临时目录,但可以很容易地适应使用createFileAtPath:contents:attributes:而不是createDirectoryAtPath:创建文件。

回答by fzwo

If targeting iOS 6.0 or Mac OS X 10.8 or higher:

如果面向 iOS 6.0 或 Mac OS X 10.8 或更高版本:

NSString *tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];

回答by Bart van Kuik

Swift 5 and Swift 4.2

Swift 5 和 Swift 4.2

import Foundation

func pathForTemporaryFile(with prefix: String) -> URL {
    let uuid = UUID().uuidString
    let pathComponent = "\(prefix)-\(uuid)"
    var tempPath = URL(fileURLWithPath: NSTemporaryDirectory())
    tempPath.appendPathComponent(pathComponent)
    return tempPath
}

let url = pathForTemporaryFile(with: "blah")
print(url)
// file:///var/folders/42/fg3l5j123z6668cgt81dhks80000gn/T/johndoe.KillerApp/blah-E1DCE512-AC4B-4EAB-8838-547C0502E264

Or alternatively Ssswift's oneliner:

或者 Ssswift 的 oneliner:

let prefix = "blah"
let url2 = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(prefix)-\(UUID())")
print(url2)

回答by Ssswift

The modern way to do this is FileManager's url(for:in:appropriateFor:create:).

执行此操作的现代方法是FileManager's url(for:in:appropriateFor:create:)

With this method, you can specify a SearchPathDirectoryto say exactly what kind of temporary directory you want. For example, a .cachesDirectorywill persist between runs (as possible) and be saved in the user's library, while a .itemReplacementDirectorywill be on the same volume as the target file.

使用此方法,您可以指定 aSearchPathDirectory来准确说明您想要什么样的临时目录。例如, a.cachesDirectory将在运行之间(尽可能)持续存在并保存在用户的库中,而 a.itemReplacementDirectory将与目标文件位于同一卷上。

回答by Giao

You could use mktempto get a temp filename.

您可以使用mktemp来获取临时文件名。

回答by alextgordon

You could use an NSTaskto uuidgento get a unique file name, then append that to a string from NSTemporaryDirectory(). This won't work on Cocoa Touch. It is a bit long-winded though.

您可以使用NSTasktouuidgen来获取唯一的文件名,然后将其附加到来自NSTemporaryDirectory(). 这不适用于 Cocoa Touch。不过有点啰嗦。