【问题标题】:Creating a file with a file name which did not exist already in that folder using objective c使用目标 c 创建一个文件名不存在于该文件夹中的文件
【发布时间】:2013-12-15 12:34:55
【问题描述】:

我想在文件目录中创建一个名为simpleFile.txt 的文件。现在,如果这个simpleFile.txt 已经存在,我想创建另一个同名但附加文件号的文件,比如simpleFile1.txt

【问题讨论】:

  • 到目前为止你有什么代码?它做错了什么?

标签: ios objective-c nsfilemanager nsdocumentdirectory


【解决方案1】:

为此目的使用一个while循环,如下所示

NSFileManager *manager = [NSFileManager defaultManager];
int i = 1;

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [documentPath objectAtIndex:0];
NSString *newFileName = [documentPath stringByAppendingPathComponent:@"simpleFile.txt"];

while ([manager fileExistsAtPath:newFileName]) {
    NSString *testName = [NSString stringWithFormat:@"simpleFile%d.txt", i];
    newFileName = [documentPath stringByAppendingPathComponent:testName];
    i++;
}

【讨论】:

  • 您的意思是fileExistsAtPath:newFileName 并想初始化newFileName
  • 您仍然需要使用默认文件的路径初始化newFileName(此时您将针对nil 进行初始测试)。
  • @Wain 是否可以检查文件名中包含“simpleFile”的文件数
  • 可以得到目录中的文件名列表,用谓词过滤数组,然后得到结果数组中对象的个数...
猜你喜欢
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 2017-05-18
  • 2015-01-25
  • 1970-01-01
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多