「hoge_file.txt」というファイル名が既にあった場合は「hoge_file-2.txt」になります。
呼び出し側
NSString *uniqueFileName = [HogeUtil getUniqueFileNameInDocumentDirectory:@"hoge_file" type:@"txt"];
HogeUtil.m
+ (NSString*)getUniqueFileNameInDocumentDirectory:(NSString*)_name type:(NSString*)_type {
NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,YES);
NSString *documentDirectory = [filePaths objectAtIndex:0];
NSString* fileName = [NSString stringWithFormat:@"%@.%@", _name, _type];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:fileName];
int i = 1;
while ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
++i;
filePath = [NSString stringWithFormat:@"%@/%@-%d.%@", documentDirectory, _name, i, _type];
fileName = [NSString stringWithFormat:@"%@-%d.%@", _name, i, _type];
}
return fileName;
}
~~~