ios - 重命名文件(如果文件已存在)

标签 ios objective-c nsdata nsfilemanager

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

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

我在下面提供了我的解决方案作为答案,但是我认为应该有一个更好的方法(内置函数)来实现。

我的解决方案不是线程安全的,并且容易出现竞争情况。

最佳答案

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

    //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];

关于ios - 重命名文件(如果文件已存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12202737/

相关文章:

ios - 将字符串传递给第二个 View Controller

ios - 解析 : PFObject is loaded without Attributes

ios - 带分段控制的多线程iOS

iphone - UIWebView 不接受多次触摸

objective-c - 屏幕 A -> 按下按钮 > 10 秒操作 -> 它需要显示屏幕 B(我使用 Storyboard)

iphone - 将 HEX NSString 转换为 NSData

ios - 我是否需要在 DispatchQueue.main.async 中使用 autoreleasepool block

ios - 增加高度约束,拉伸(stretch) "Runtime added subviews"

iphone - 修改文件 iOS 中的数据(字节)

swift - 在 Swift 3 中将数据写入 NSOutputStream