How do I create a temporary file with Cocoa?
I created a pure Cocoa solution by way of a category on NSFileManager
that uses a combination of NSTemporary()
and a globally unique 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.
A safe way is to use mkstemp(3).
Apple has provided an excellent way for accessing temp directory and creating unique names for the temp files.
- (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
[Note: This applies to the iPhone SDK, not the 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:
[NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @"txt"]];
Not the prettiest, but functional