1

如果存在同名文件,那么在objective-c中重命名文件的最佳方法是什么。

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

我在下面包含了我的解决方案作为答案,但我认为应该有更好的方法(内置函数)来做到这一点。

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

4

1 回答 1

6

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

    //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];
于 2012-08-30T17:55:42.607 回答