Nsfilemanager unikalne nazwy plików

Potrzebuję szybkiego i łatwego sposobu przechowywania plików z unikalnymi nazwami plików na iOS. Muszę przedrostek pliku z ciągiem znaków, a następnie dołączyć wygenerowany unikalny identyfikator do końca. Miałem nadzieję, że NSFileManager ma jakąś wygodną metodę, aby to zrobić, ale nie mogę jej znaleźć.

Patrzyłem na createFileAtPath:contents:attributes:, ale nie jestem pewien, czy atrybuty dadzą mi tę unikalną nazwę pliku.

Author: Josh Caswell, 2011-10-13

8 answers

Utwórz własną nazwę pliku:

CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef uuidString = CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
NSString *uniqueFileName = [NSString stringWithFormat:@"%@%@", prefixString, (NSString *)uuidString];
CFRelease(uuidString);

Prostsza alternatywa zaproponowana przez @ darrinm w komentarzach:

NSString *prefixString = @"MyFilename";

NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString] ;
NSString *uniqueFileName = [NSString stringWithFormat:@"%@_%@", prefixString, guid];

NSLog(@"uniqueFileName: '%@'", uniqueFileName);

Wyjście NSLog:
uniqueFileName: 'MyFilename_680E77F2-20b8-444E-875B-11453B06606E-688-00000145b460af51'

Uwaga: iOS6 wprowadził klasę NSUUID, która może być używana zamiast CFUUID.

NSString *guid = [[NSUUID new] UUIDString];
 75
Author: zaph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-19 12:37:23

Używam current date do generowania losowej nazwy pliku z danym rozszerzeniem. Jest to jedna z metod w kategorii mój NSFileManager:

+ (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;
}
 8
Author: wzbozon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-25 10:18:42

Możesz również użyć czcigodnego mktemp() (patrz man 3 mktemp). Tak:

- (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];
}

XXXXX zostanie zastąpiona unikalną kombinacją liter/cyfr. Mogą one pojawiać się tylko na końcu szablonu, więc nie można dodać do niego rozszerzenia (chociaż można je dodać po uzyskaniu unikalnej nazwy pliku). Dodaj tyle X ile chcesz w szablonie.

Plik nie jest tworzony, musisz go utworzyć samodzielnie. Jeśli masz wiele wątków tworzących unikalne pliki w ten sam katalog, można uruchomić możliwość posiadania warunków wyścigu. Jeśli tak jest, Użyj mkstemp(), która utworzy plik i zwróci deskryptor pliku.

 7
Author: ovidiu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-14 18:39:13

W iOS 6 najprostszą metodą jest użycie:

NSString *uuidString = [[NSUUID UUID] UUIDString];
 5
Author: Reefwing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-15 00:30:13

Oto, czego użyłem w Swift 3.0

public func generateUniqueFilename (myFileName: String) -> String {

    let guid = ProcessInfo.processInfo.globallyUniqueString
    let uniqueFileName = ("\(myFileName)_\(guid)")

    print("uniqueFileName: \(uniqueFileName)")

    return uniqueFileName
}
 4
Author: Dave Strand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-16 15:12:12

To powinno ci się udać:

Http://vgable.com/blog/2008/02/24/creating-a-uuid-guid-in-cocoa/

Autor postu sugeruje wdrożenie metody "stringWithUUID" jako kategorii NSString. Wystarczy dopisać GUID wygenerowany za pomocą tej metody na końcu nazwy pliku, który tworzysz.

 2
Author: lottscarson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-13 19:29:00

Super-easy Swift 4 1-liner:

fileName = "MyFileName_" + UUID().uuidString

Lub

fileName = "MyFileName_" + ProcessInfo().globallyUniqueString
 1
Author: drewster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-01 21:04:09

Swift 4.1. Wystarczy podać nazwę rozszerzenia pliku, a funkcja zwróci unikalną nazwę pliku.

func uniqueFileNameWithExtention(fileExtension: String) -> String {
        let uniqueString: String = ProcessInfo.processInfo.globallyUniqueString
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyyMMddhhmmsss"
        let dateString: String = formatter.string(from: Date())
        let uniqueName: String = "\(uniqueString)_\(dateString)"
        if fileExtension.length > 0 {
            let fileName: String = "\(uniqueName).\(fileExtension)"
            return fileName
        }

        return uniqueName
    }
 0
Author: GSK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-20 15:37:12