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

lfa*_*lin 39 file-io cocoa objective-c

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

Path.GetTempFileName();
Run Code Online (Sandbox Code Playgroud)

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

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

NSTemporaryDirectory
Run Code Online (Sandbox Code Playgroud)

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

小智 35

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

  • http://cocoawithlove.com/2009/07/temporary-files-and-folders-in-cocoa.html (10认同)
  • @Chris Hanson:什么,没有x-man-page:// 3/mkstemp链接?;-) (2认同)

Ben*_*ieb 20

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

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

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

不是最漂亮但功能性的

  • 这与mktemp(3)具有相同的竞争条件:从创建临时文件中分离文件名的创建会打开一个漏洞窗口.正如Graham Lee所说,使用mkstemp(3). (5认同)
  • 在iPhone上,每个应用程序都有自己的文件系统子树.NSTemporaryDirectory()返回应用程序包中的内容.你仍然在与你自己竞争,反对任何对你的tmp dir有写权限的事情,但我认为这只是特权进程. (2认同)
  • @Ken提问者说他​​们在iPhone上的位置? (2认同)
  • 当从多个线程"同时"调用时,这会导致失败.我不知道这个方法有多精细(文档没有详细说明),但对我而言,我的NSOperations被调得太快而且文件名称相同.我的解决方案是将NSOperations地址添加到文件名,因为它们肯定会有所不同:[NSString stringWithFormat:@"%d _%.0f.%@",self,[NSDate timeInterv ... (2认同)

muz*_*uzz 16

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;
}
Run Code Online (Sandbox Code Playgroud)

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


Qui*_*lor 13

虽然差不多一年之后,我认为提起Matt Gallagher的Cocoa With Love的博客文章仍然有用.http://cocoawithlove.com/2009/07/temporary-files-and-folders-in-cocoa.html他展示了如何使用mkstemp()文件和mkdtemp()目录,完成NSString转换.


Phi*_*ipp 11

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

这里是头文件:

@interface NSFileManager (TemporaryDirectory)

-(NSString *) createTemporaryDirectory;

@end
Run Code Online (Sandbox Code Playgroud)

和实施文件:

@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
Run Code Online (Sandbox Code Playgroud)

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


fzw*_*zwo 10

如果定位到iOS 6.0或Mac OS X 10.8或更高版本:

NSString *tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
Run Code Online (Sandbox Code Playgroud)


Bar*_*uik 6

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
Run Code Online (Sandbox Code Playgroud)

或者 Ssswift 的 oneliner:

let prefix = "blah"
let url2 = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(prefix)-\(UUID())")
print(url2)
Run Code Online (Sandbox Code Playgroud)

  • 此代码不再有效,但等效版本更简单:`URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(prefix)-\(UUID())")` (2认同)