4
2

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.

Objective-C ファイル操作の基本(確認、作成、コピー、削除、抽出)

Last updated at Posted at 2017-11-24

NSFileManagerを使ったやり方 (備忘録)

ファイル・ディレクトリの存在確認

Objective-C
NSString *path = ...

if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
    // not exists
} else {
    // exists
}

ディレクトリかどうかを調べる

Objective-C
+ (BOOL)isDirectory:(NSString*)path
{
    BOOL isDir;
    if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
        if (isDir) {
            return YES;
        }
    }
    return NO;
}

ついでに存在チェックも行なっている。

ディレクトリを作成

Objective-C
NSString *path = ...

[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];

withIntermediateDirectories: YES ...上位階層のディレクトリを自動的に作成する

ファイル・ディレクトリをコピー

Objective-C
NSString *src = ...
NSString *dst = ...

[[NSFileManager defaultManager] copyItemAtPath:src toPath:dst error:nil];

※ディレクトリ毎、ファイルもコピーされます。

ファイル・ディレクトリを削除

Objective-C
NSString *path = ...

[[NSFileManager defaultManager] removeItemAtPath:path error:nil];

※ディレクトリ毎、ファイルも削除されます。

指定ディレクトリのファイルのみを抽出 (再帰的)

Objective-C
NSString *path = ...

NSFileManager *fileMamager = [NSFileManager defaultManager];
NSDirectoryEnumerator *enumerator = [fileMamager enumeratorAtPath:path];
NSString *name;
BOOL isDir;
while (name = [enumerator nextObject]) {
    NSString *fullPath = [path stringByAppendingPathComponent:name];
    [fileMamager fileExistsAtPath:fullPath isDirectory:&isDir];
    if (!isDir) {
        NSLog(@"%@", fullPath);
    }
}
4
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?