如果文件已存在,则重命名文件

时间:2012-08-30 17:55:43

标签: ios objective-c nsdata nsfilemanager

如果存在具有相同名称的文件,objective-c中重命名文件的最佳方式是什么。

理想情况下,如果名为untitled.png的文件已存在,我想将untitled.png命名为untitled-1.png。

我已将下面的解决方案作为答案包含在内,但我认为应该有更好的方法(内置函数)来实现它。

我的解决方案不是线程安全的,并且容易受到竞争条件的影响。

1 个答案:

答案 0 :(得分:5)

以下函数返回下一个可用文件名:

    //returns next available unique filename (with suffix appended)
- (NSString*) getNextAvailableFileName:(NSString*)filePath suffix:(NSString*)suffix
{   

    NSFileManager* fm = [NSFileManager defaultManager];

    if ([fm fileExistsAtPath:[NSString stringWithFormat:@"%@.%@",filePath,suffix]]) {
        int maxIterations = 999;
        for (int numDuplicates = 1; numDuplicates < maxIterations; numDuplicates++)
        {
            NSString* testPath = [NSString stringWithFormat:@"%@-%d.%@",filePath,numDuplicates,suffix];
            if (![fm fileExistsAtPath:testPath])
            {
                return testPath;
            }
        }
    }

    return [NSString stringWithFormat:@"%@.%@",filePath,suffix];
}

示例调用函数如下:

    //See" http://stackoverflow.com/questions/1269214/how-to-save-an-image-that-is-returned-by-uiimagepickerview-controller

    // Get the image from the result
    UIImage* image = [info valueForKey:@"UIImagePickerControllerOriginalImage"];

    // Get the data for the image as a PNG
    NSData* imageData = UIImagePNGRepresentation(image);

    // Give a name to the file
    NSString* imageName = @"image";
    NSString* suffix = @"png";


    // Now we get the full path to the file
    NSString* filePath = [currentDirectory stringByAppendingPathComponent:imageName];

    //If file already exists, append unique suffix to file name
    NSString* fullPathToFile = [self getNextAvailableFileName:filePath suffix:suffix];

    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];