iOSアプリ開発の逆引き辞典

iPhone/iPadで使えるアプリ開発のTipsをまとめてみました

NSMutableDataを使ってテキストをDocumentディレクトリへ保存する

Documentディレクトリのパスを取得する

Documentディレクトリのパスは、NSSearchPathForDirectoriesInDomains関数NSDocumentDirectoryを指定すると取得する事が出来ます。

NSArray* paths = NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory, NSUserDomainMask, YES);
NSString* docDir = [paths objectAtIndex:0];

Document配下にディレクトリを作成する

Documentディレクトリ配下のcacheディレクトリにファイルを配置したい場合は、ディレクトリが存在しない可能性があります。

ディレクトリが存在するのかどうかを確認して、存在しなかった場合ディレクトリを作成します。

NSString* dirPath = [NSString stringWithFormat:@"%@/cache", docDir];
NSFileManager* fileManager = [NSFileManager defaultManager];
// ディレクトリが存在するか確認する
if (![fileManager fileExistsAtPath:dirPath])
{
    // 存在しなければ、ディレクトリを作成する
    [fileManager createDirectoryAtPath:dirPath 
           withIntermediateDirectories:YES 
            attributes:nil error:nil];
}

これで書き込む為の準備ができました。

データを書き込む

ほげぴよを用意します。テキストからバイト列を作成して、NSMutableDataオブジェクトにappendData:メソッドを使ってデータの末尾に追加していきます。

// 書き込みたい文字列を用意しておきます(適当にほげとぴよを用意)
NSString* hoge = @"ほげ";
NSString* piyo = @"ぴよ";
    
// テキストからバイト列を作成する 
NSData* dataHoge = [hoge dataUsingEncoding:NSUTF8StringEncoding];
NSData* dataPiyo = [piyo dataUsingEncoding:NSUTF8StringEncoding];
    
// 保存するデータを用意する
NSMutableData* data = [NSMutableData data];
[data appendData:dataHoge];
[data appendData:dataPiyo];
    
// データの書き込み
NSString *filePath = [NSString stringWithFormat:@"%@/hogehoge.txt", dirPath];
[data writeToFile:filePath atomically:YES];

これでテキストをDocumentディレクトリへ保存することが出来ました。