簡體   English   中英

如何使用 Cocoa 創建臨時文件?

[英]How do I create a temporary file with Cocoa?

多年前,當我使用 C# 時,我可以輕松地創建一個臨時文件並使用此函數獲取其名稱:

Path.GetTempFileName();

此函數將在臨時目錄中創建一個具有唯一名稱的文件,並返回該文件的完整路徑。

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

NSTemporaryDirectory

我是否遺漏了一些明顯的東西,或者沒有內置的方法來做到這一點?

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

[注意:這適用於 iPhone SDK,不適用於 Mac OS SDK]

據我所知,這些函數不存在於 SDK 中(與標准 Mac OS X 10.5 文件相比, unistd.h文件被大幅縮減)。 我會使用以下內容:

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

不是最漂亮,但功能強大

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

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

雖然差不多一年之后,我認為提起Matt Gallagher的Cocoa With Love的博客文章仍然有用。 http://cocoawithlove.com/2009/07/temporary-files-and-folders-in-cocoa.html他展示了如何將mkstemp()用於文件,將mkdtemp()用於目錄,並完成NSString轉換。

我創建由一個類別的方式純可可溶液NSFileManager使用的組合NSTemporary()和一個全局唯一ID。

這里的頭文件:

@interface NSFileManager (TemporaryDirectory)

-(NSString *) createTemporaryDirectory;

@end

和實現文件:

@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

這會創建一個臨時目錄,但可以很容易地適應使用createFileAtPath:contents:attributes:而不是createDirectoryAtPath:來創建文件。

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

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

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

或者 Ssswift 的 oneliner:

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

您可以使用mktemp來獲取臨時文件名。

現代方法是FileManagerurl(for:in:appropriateFor:create:)

使用這種方法,您可以指定一個SearchPathDirectory來准確說明您想要什么樣的臨時目錄。 例如, .cachesDirectory將在運行之間(盡可能)保持並保存在用戶的庫中,而.itemReplacementDirectory將與目標文件位於同一卷上。

您可以使用NSTaskuuidgen來獲取唯一的文件名,然后將其附加到來自NSTemporaryDirectory()的字符串。 這不適用於 Cocoa Touch。 不過有點啰嗦。

添加到@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;
}

不要使用像NSTemporaryDirectory這樣的遺留 API,而是從FileManager獲取正確的URL

let tmpURL = FileManager
    .default
    .temporaryDirectory
    .appendingPathComponent(UUID().uuidString)

您仍然需要創建目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM