Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFileManager unique file names

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 end. I was hoping NSFileManager had some convenient method to do this, but I can't seem to find it.

I was looking at createFileAtPath:contents:attributes:, but am unsure if the attributes will give me that unique file name.

like image 205
spentak Avatar asked Oct 13 '11 19:10

spentak


People also ask

What is a good example of a file name?

A file name is the complete title of a file and file extension. For example, "readme. txt" is a complete file name. A file name may also describe only the first portion of the file.

What are the parts of a file name?

Windows file names have two parts; the file's name, then a period followed by the extension (suffix).

What are the two names of a file?

Windows files has two parts the files name , the a period followed by the extension is a three- or four letter abbreviation that signifies the file type. for example in letter.


Video Answer


2 Answers

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]; 
like image 176
zaph Avatar answered Oct 04 '22 04:10

zaph


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; } 
like image 42
Denis Kutlubaev Avatar answered Oct 04 '22 05:10

Denis Kutlubaev