u16suzuの blog

日々学んだことのメモブログです。

データを永続化する。

データを永続化するというのは、iPhoneにデータを保存するということ。 NSUserDefault でもデータ保存はできるけど、これはユーザが設定したアプリの設定項目に使用するべきで アプリ内で定義したモデルの情報を保存することに使うべきではない。

以下の方法を使うと、/Documents 以下に保存される。

NSArray  *array = @[@"hoge", @"fuga", @1, @2, @3];
NSDictionary *dic = @{@"hoge": @1, @"fuga": @2};
NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *filePath = [directory stringByAppendingPathComponent:@"data3.dat"];

// オブジェクトの保存
if ( [NSKeyedArchiver archiveRootObject:array toFile:filePath] ){
    NSLog(@"%@", @"データの保存に成功しました。");
}
// オブジェクトの復元
NSArray *res = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@", res);

Snipet登録したいけど微妙

参考: http://d.hatena.ne.jp/glass-_-onion/20110904/1315145330