hachinoBlog

hachinobuのエンジニアライフ

plistに書き込んだ値が実機だと保存されない事象

自分でリソースフォルダに作成したsample.plistに情報を書き込んだが確認したところ保存されていなかった。
失敗したコードは下記

NSString* path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"plist"];

//plistファイルの読み込み
NSMutableArray* samples = [NSMutableArray arrayWithContentsOfFile:path];

//plistに追記
[samples addObject:@"sample1"];
[samples addObject:@"sample2"];

//保存
[samples writeToFile:path atomically:NO];

原因はplistの配置場所が問題だった。
書き込み権限のあるAppData配下にファイルを配置してあげないと書き込みできない。
今回はNSCachesDirectoryに移動してから情報を書き込むことにした。
修正したコードは下記

NSString* path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"plist"];

//Cacheディレクトリ
NSString *cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"sample.plist"];

NSFileManager *filemanager = [NSFileManager defaultManager];
if (![filemanager fileExistsAtPath:cachePath]) {
    [filemanager copyItemAtPath:path toPath:cachePath error:nil];
}

//plistファイルの読み込み
NSMutableArray* samples = [NSMutableArray arrayWithContentsOfFile:cachePath];

//plistに追記
[samples addObject:@"sample1"];
[samples addObject:@"sample2"];

//保存
[samples writeToFile:cachePath atomically:NO];

これで書き込みして保存できる。