OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 objective-c 创建一个文件名不存在于该文件夹中的文件 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 05:35
标题: ios - 使用 objective-c 创建一个文件名不存在于该文件夹中的文件

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



Best Answer-推荐答案


为此目的使用一个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++;
}

关于ios - 使用 objective-c 创建一个文件名不存在于该文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20283625/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4