4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOS ユニークなファイル名をつける

Last updated at Posted at 2013-08-05

「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;
}
~~~
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?