如何在 iOS 的文档目录中保存带有唯一标签的文件?

问题描述 投票:0回答:2

注意:文件名由用户指定

在我的一个应用程序中,我需要在文档目录中使用任何唯一标签创建文件(最好在字符串中给出标签!)。

我已经搜索过了,但没有成功。我知道如何在文档目录中创建文件,但卡在给它唯一的标签。

如果有人做过,请告诉我该怎么做。

ios objective-c iphone tags nsfilemanager
2个回答
2
投票

我已经使用时间间隔来保存独特的文件。

int timestamp = [[NSDate date] timeIntervalSince1970];

NSString *fileName = [NSString stringWithFormat:@"%d",timestamp];

编辑:

// Or As you said if the user gives fileName.

NSString *userFileName = [NSString stringWithFormat:@"%@_%d",USER_GIVEN_NAME,timestamp];

// Here USER_GIVEN_NAME is a string that is the file name from the user.

用户是否提供相同的名称并不重要,因为每当您尝试保存文件时,时间间隔都会更改并返回新的时间间隔。


0
投票

您可以使用时间戳(如 Kampai 的答案),或者您可以在文件名后附加日期以使名称唯一,如下面的代码

NSCalendar *sysCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
df.calendar = sysCalendar;
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:@"mmddyyyyHHmmss"];
NSString *strDate = [df stringFromDate:[NSDate date]];

NSString *name = [NSString stringWithFormat:@"%@_%@",@"yourfilename",strDate];

也许这会对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.