NSFileManager唯一的文件名 [英] NSFileManager unique file names

查看:208
本文介绍了NSFileManager唯一的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

I was looking at createFileAtPath:contents:attributes:, but am unsure if the attributes will give me that unique file name.

推荐答案

创建自己的文件名:

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

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

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输出:

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

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

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

Note: iOS6 introduced the NSUUID class which can be used in place of CFUUID.

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

这篇关于NSFileManager唯一的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆