NSFileManager unique file names

前端 未结 9 1891
生来不讨喜
生来不讨喜 2020-12-23 10:54

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

相关标签:
9条回答
  • 2020-12-23 11:42

    This should probably work for you:

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

    The author of the post suggests implementing a 'stringWithUUID' method as a category of NSString. Just append a GUID generated with this method to the end of the file name that you're creating.

    0 讨论(0)
  • 2020-12-23 11:44

    Super-easy Swift 4 1-liner:

    fileName = "MyFileName_" + UUID().uuidString
    

    or

    fileName = "MyFileName_" + ProcessInfo().globallyUniqueString
    
    0 讨论(0)
  • 2020-12-23 11:52

    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];
    
    0 讨论(0)
提交回复
热议问题