ios NSFileManager 唯一文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7759220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSFileManager unique file names
提问by spentak
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.
我需要一种快速简便的方法来在 iOS 上存储具有唯一文件名的文件。我需要用字符串作为文件前缀,然后将生成的唯一标识符附加到末尾。我希望NSFileManager
有一些方便的方法来做到这一点,但我似乎无法找到它。
I was looking at createFileAtPath:contents:attributes:
, but am unsure if the attributes will give me that unique file name.
我正在查看createFileAtPath:contents:attributes:
,但不确定这些属性是否会给我唯一的文件名。
回答by zaph
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:
uniqueFileName: 'MyFilename_680E77F2-20B8-444E-875B-11453B06606E-688-00000145B460AF51'
NSLog 输出:
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];
回答by Denis Kutlubaev
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; }
回答by ovidiu
You can also use the venerable mktemp()
(see man 3 mktemp
). Like this:
您还可以使用可敬的mktemp()
(请参阅参考资料man 3 mktemp
)。像这样:
- (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. 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.
该XXXXX
会以独特的字母/数字组合所取代。它们只能出现在模板的末尾,因此您不能在模板中附加扩展名(尽管您可以在获得唯一文件名后附加它)。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()
which 创建文件并返回文件描述符。
回答by Reefwing
In iOS 6 the simplest method is to use:
在 iOS 6 中,最简单的方法是使用:
NSString *uuidString = [[NSUUID UUID] UUIDString];
回答by Dave Levy
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
}
回答by drewster
Super-easy Swift 41-liner:
超级简单的Swift 41-liner:
fileName = "MyFileName_" + UUID().uuidString
or
或者
fileName = "MyFileName_" + ProcessInfo().globallyUniqueString
回答by lottscarson
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. Just append a GUID generated with this method to the end of the file name that you're creating.
该帖子的作者建议将“stringWithUUID”方法实现为 NSString 的类别。只需将使用此方法生成的 GUID 附加到您正在创建的文件名的末尾。
回答by Golompse
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)
}
}
回答by Gurjinder Singh
Swift 4.1. Just pass you file extension name and function will return unique file name.
斯威夫特 4.1。只需传递文件扩展名,函数将返回唯一的文件名。
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
}