I wish NSFileManager
had something like Java’s java.io.File.createTemporaryFile
, but it doesn’t.
So I added it with a Category. Wonderful thing, Objective-C categories.
The project is up on GitHub, but I thought I’d include just the code here as well:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
-(NSURL*)createTemporaryFile:(NSString*)prefix suffix:(NSString*)suffix in:(NSURL*)parentFolder onError:(NSError**)error { NSURL * ret_val = nil; __autoreleasing NSError * tempError; error = error == NULL ? &tempError : error; prefix = prefix == nil ? @"" : prefix; suffix = suffix == nil ? @"" : suffix; NSString * tempAsPath= [parentFolder path]; BOOL parentIsDir = NO; [self fileExistsAtPath:tempAsPath isDirectory:&parentIsDir]; NSString * format = parentIsDir ? @"%@/%@XXXXX%@" : @"%@%@XXXXX%@"; NSString * path_template = [NSString stringWithFormat:format, tempAsPath, prefix, suffix]; const char * path_template_cstr = [path_template fileSystemRepresentation]; char * tempFileNameCString = (char *)malloc(strlen(path_template_cstr) + 1); strcpy(tempFileNameCString, path_template_cstr); int fd = mkstemps(tempFileNameCString, (int)strlen ( [suffix UTF8String] ) ); if ( fd == -1 ) *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:nil]; else { close ( fd ); NSString * tempFilePath = [self stringWithFileSystemRepresentation:tempFileNameCString length:strlen(tempFileNameCString)]; ret_val = [NSURL fileURLWithPath:tempFilePath]; } free(tempFileNameCString); return ret_val; } |