如果存在同名文件,在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/