简体   繁体   English

NSFileManager 唯一文件名

[英]NSFileManager unique file names

I need a quick and easy way to store files with unique file names on iOS.我需要一种快速简便的方法来在 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.我希望NSFileManager有一些方便的方法来做到这一点,但我似乎找不到它。

I was looking at createFileAtPath:contents:attributes: , but am unsure if the attributes will give me that unique file name.我正在查看createFileAtPath:contents:attributes: ,但不确定这些属性是否会给我唯一的文件名。

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: @darrinm 在评论中提出了一个更简单的替代方案:

NSString *prefixString = @"MyFilename";

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

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

NSLog output: NSLog 输出:
uniqueFileName: 'MyFilename_680E77F2-20B8-444E-875B-11453B06606E-688-00000145B460AF51' uniqueFileName: 'MyFilename_680E77F2-20B8-444E-875B-11453B06606E-688-00000145B460AF51'

Note: iOS6 introduced the NSUUID class which can be used in place of CFUUID.注意:iOS6 引入了 NSUUID 类,可以用来代替 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:这是我的 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;
}

You can also use the venerable mktemp() (see man 3 mktemp ).您还可以使用古老的mktemp() (请参阅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. XXXXX将替换为唯一的字母/数字组合。 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.在模板中添加任意数量的X

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.如果是这种情况,请使用mkstemp()创建文件并返回文件描述符。

Super-easy Swift 4 1-liner:超级简单的Swift 4 1-liner:

fileName = "MyFileName_" + UUID().uuidString

or或者

fileName = "MyFileName_" + ProcessInfo().globallyUniqueString

在 iOS 6 中,最简单的方法是使用:

NSString *uuidString = [[NSUUID UUID] UUIDString];

Here is what I ended up using in Swift 3.0这是我最终在 Swift 3.0 中使用的

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

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

    print("uniqueFileName: \(uniqueFileName)")

    return uniqueFileName
}

Swift 4.1 and 5 .斯威夫特 4.15 Just pass you file extension name and function will return unique file name.只需传递文件扩展名,函数将返回唯一的文件名。

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
    }

Swift 4.2, I use two options, one mostly unique but readable, and the other just unique. Swift 4.2,我使用了两个选项,一个主要是独特但可读的,另一个只是独特的。

// Create a unique filename, added to a starting string or not
public func uniqueFilename(filename: String = "") -> String {
    let uniqueString = ProcessInfo.processInfo.globallyUniqueString
    return filename + "-" + uniqueString
}

// Mostly Unique but Readable ID based on date and time that is URL compatible ("unique" to nearest second)
public func uniqueReadableID(name: String = "") -> String {

    let timenow = DateFormatter.localizedString(from: Date(), dateStyle: .medium, timeStyle: .medium)
    let firstName = name + "-" + timenow
    do {
        // Make ID compatible with URL usage
        let regex = try NSRegularExpression(pattern: "[^a-zA-Z0-9_]+", options: [])
        let newName = regex.stringByReplacingMatches(in: firstName, options: [], range: NSMakeRange(0, firstName.count), withTemplate: "-")
        return newName
    }
    catch {
        print("🧨 Unique ID Error: \(error.localizedDescription)")
        return uniqueFilename(filename: name)
    }
}

This should probably work for you:这可能对你有用:

http://vgable.com/blog/2008/02/24/creating-a-uuid-guid-in-cocoa/ 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.该帖子的作者建议将“stringWithUUID”方法实现为 NSString 的类别。 Just append a GUID generated with this method to the end of the file name that you're creating.只需将使用此方法生成的 GUID 附加到您正在创建的文件名的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM