NSFileManager unique file names
Create your own file name:
CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef uuidString = CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
NSString *uniqueFileName = [NSString stringWithFormat:@"%@%@", prefixString, (NSString *)uuidString];
CFRelease(uuidString);
A simpler alternative proposed by @darrinm in the comments:
NSString *prefixString = @"MyFilename";
NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString] ;
NSString *uniqueFileName = [NSString stringWithFormat:@"%@_%@", prefixString, guid];
NSLog(@"uniqueFileName: '%@'", uniqueFileName);
NSLog output:
uniqueFileName: 'MyFilename_680E77F2-20B8-444E-875B-11453B06606E-688-00000145B460AF51'
Note: iOS6 introduced the NSUUID class which can be used in place of CFUUID.
NSString *guid = [[NSUUID new] UUIDString];
I use current date to generate random file name with a given extension. This is one of the methods in my NSFileManager category:
+ (NSString*)generateFileNameWithExtension:(NSString *)extensionString { // Extenstion string is like @".png" NSDate *time = [NSDate date]; NSDateFormatter* df = [NSDateFormatter new]; [df setDateFormat:@"dd-MM-yyyy-hh-mm-ss"]; NSString *timeString = [df stringFromDate:time]; NSString *fileName = [NSString stringWithFormat:@"File-%@%@", timeString, extensionString]; return fileName; }
Super-easy Swift 4 1-liner:
fileName = "MyFileName_" + UUID().uuidString
or
fileName = "MyFileName_" + ProcessInfo().globallyUniqueString