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

时间:2022-09-08 02:50:23

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?

我错过了一些明显的东西,还是没有内置的方法来做到这一点?

11 个解决方案

#1


36  

A safe way is to use mkstemp(3).

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

#2


19  

[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.h file is drastically pared down when compared to the standard Mac OS X 10.5 file). I would use something along the lines of:

据我所知,SDK中没有这些功能(与标准Mac OS X 10.5文件相比,unistd.h文件大幅减少)。我会使用以下内容:

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

Not the prettiest, but functional

不是最漂亮的,但功能性的

#3


16  

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/DTS40009245 see file :::AppDelegate.m

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

#4


12  

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.html He 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转换。

#5


11  

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

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

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:来创建一个文件。

#6


8  

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]];

#7


2  

You could use mktemp to get a temp filename.

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

#8


1  

Updated for Swift 3, copied straight from a Playground:

更新为Swift 3,直接从游乐场复制:

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)

#9


1  

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

现代的方法是FileManager的url(for:in:properFor:create :)。

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

使用此方法,您可以指定SearchPathDirectory来准确说出所需的临时目录类型。例如,.cachesDirectory将在运行之间保持(尽可能)并保存在用户的库中,而.itemReplacementDirectory将与目标文件位于同一个卷上。

#10


0  

You could use an NSTask to uuidgen to 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.

您可以使用NSTask来uuidgen获取唯一的文件名,然后将其附加到NSTemporaryDirectory()的字符串中。这对Cocoa Touch无效。虽然有点啰嗦。

#11


0  

Adding to @Philipp:

添加到@Philipp:

- (NSString *)createTemporaryFile:(NSData *)contents {
    // Create a unique file in the system temporary directory
    NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];
    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:guid];
    if(![self createFileAtPath:path contents:contents attributes:nil]) {
        return nil;
    }
    return path;
}

#1


36  

A safe way is to use mkstemp(3).

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

#2


19  

[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.h file is drastically pared down when compared to the standard Mac OS X 10.5 file). I would use something along the lines of:

据我所知,SDK中没有这些功能(与标准Mac OS X 10.5文件相比,unistd.h文件大幅减少)。我会使用以下内容:

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

Not the prettiest, but functional

不是最漂亮的,但功能性的

#3


16  

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/DTS40009245 see file :::AppDelegate.m

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

#4


12  

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.html He 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转换。

#5


11  

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

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

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:来创建一个文件。

#6


8  

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]];

#7


2  

You could use mktemp to get a temp filename.

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

#8


1  

Updated for Swift 3, copied straight from a Playground:

更新为Swift 3,直接从游乐场复制:

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)

#9


1  

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

现代的方法是FileManager的url(for:in:properFor:create :)。

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

使用此方法,您可以指定SearchPathDirectory来准确说出所需的临时目录类型。例如,.cachesDirectory将在运行之间保持(尽可能)并保存在用户的库中,而.itemReplacementDirectory将与目标文件位于同一个卷上。

#10


0  

You could use an NSTask to uuidgen to 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.

您可以使用NSTask来uuidgen获取唯一的文件名,然后将其附加到NSTemporaryDirectory()的字符串中。这对Cocoa Touch无效。虽然有点啰嗦。

#11


0  

Adding to @Philipp:

添加到@Philipp:

- (NSString *)createTemporaryFile:(NSData *)contents {
    // Create a unique file in the system temporary directory
    NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];
    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:guid];
    if(![self createFileAtPath:path contents:contents attributes:nil]) {
        return nil;
    }
    return path;
}