同じ名前のファイルが存在する場合、objective-c でファイルの名前を変更する最良の方法は何ですか?
理想的には、untitled.png という名前のファイルが既に存在する場合は、untitled.png を untitled-1.png に名前を付けたいと思います。
回答として以下のソリューションを含めましたが、それを行うためのより良い方法 (組み込み関数) があるはずです。
私のソリューションはスレッドセーフではなく、競合状態の影響を受けやすくなっています。
同じ名前のファイルが存在する場合、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];