NSFileManager 唯一文件名

发布于 2024-12-09 20:30:08 字数 189 浏览 1 评论 0原文

我需要一种快速、简单的方法来在 iOS 上存储具有唯一文件名的文件。我需要在文件前面加上一个字符串前缀,然后将生成的唯一标识符附加到末尾。我希望 NSFileManager 有一些方便的方法来做到这一点,但我似乎找不到它。

我正在查看 createFileAtPath:contents:attributes:,但不确定属性是否会给我唯一的文件名。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

怀里藏娇 2024-12-16 20:30:08

创建您自己的文件名:

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

@darrinm 在评论中提出的更简单的替代方案:

NSString *prefixString = @"MyFilename";

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

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

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

注意:iOS6 引入了 NSUUID 类,可以用来代替 CFUUID。

NSString *guid = [[NSUUID new] UUIDString];

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];
相权↑美人 2024-12-16 20:30:08

超级简单的Swift 4 1-liner:

fileName = "MyFileName_" + UUID().uuidString

fileName = "MyFileName_" + ProcessInfo().globallyUniqueString

Super-easy Swift 4 1-liner:

fileName = "MyFileName_" + UUID().uuidString

or

fileName = "MyFileName_" + ProcessInfo().globallyUniqueString
梦里梦着梦中梦 2024-12-16 20:30:08

我使用当前日期生成具有给定扩展名的随机文件名。这是我的 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;
}

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;
}
雪若未夕 2024-12-16 20:30:08

您还可以使用古老的 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];
}

XXXXX 将被替换为唯一的字母/数字组合。它们只能出现在模板的末尾,因此您不能在模板中附加扩展名(尽管您可以在获得唯一文件名后附加它)。在模板中添加任意数量的 X

该文件没有创建,需要您自己创建。如果您有多个线程在同一目录中创建唯一的文件,则可能会出现竞争条件。如果是这种情况,请使用 mkstemp() 创建文件并返回文件描述符。

You can also use the venerable mktemp() (see 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. 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.

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.

第几種人 2024-12-16 20:30:08

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

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

In iOS 6 the simplest method is to use:

NSString *uuidString = [[NSUUID UUID] UUIDString];
最笨的告白 2024-12-16 20:30:08

这是我最终在 Swift 3.0 中使用的

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

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

    print("uniqueFileName: \(uniqueFileName)")

    return uniqueFileName
}

Here is what I ended up using in Swift 3.0

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

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

    print("uniqueFileName: \(uniqueFileName)")

    return uniqueFileName
}
苍景流年 2024-12-16 20:30:08

Swift 4.15。只需传递您的文件扩展名,函数就会返回唯一的文件名。

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.1 and 5. 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
    }
跨年 2024-12-16 20:30:08

这可能适合您:

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

帖子的作者建议实现“stringWithUUID”方法作为 NSString 的类别。只需将使用此方法生成的 GUID 附加到您正在创建的文件名的末尾即可。

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.

把回忆走一遍 2024-12-16 20:30:08

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("

Swift 4.2, I use two options, one mostly unique but readable, and the other just unique.

// 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)
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文