I need a quick and easy way to store files with unique file names on iOS. I need to prefix the file with a string, and then append the generated unique identifier to the en
You can also use the venerable mktemp() (see man 3 mktemp). Like this:
- (NSString*)createTempFileNameInDirectory:(NSString*)dir
{
NSString* templateStr = [NSString stringWithFormat:@"%@/filename-XXXXX", dir];
char template[templateStr.length + 1];
strcpy(template, [templateStr cStringUsingEncoding:NSASCIIStringEncoding]);
char* filename = mktemp(template);
if (filename == NULL) {
NSLog(@"Could not create file in directory %@", dir);
return nil;
}
return [NSString stringWithCString:filename encoding:NSASCIIStringEncoding];
}
The XXXXX will be replaced with a unique letter/number combination. They can only appear at the end of the template, so you cannot have an extension appended in the template (though you can append it after the unique file name is obtained). Add as many X as you want in the template.
The file is not created, you need to create it yourself. If you have multiple threads creating unique files in the same directory, you run the possibility of having race conditions. If this is the case, use mkstemp() which creates the file and returns a file descriptor.