アプリで生成したデータを永続的に(アプリを終了しても消えないように)保存する方法のひとつに、「プロパティリストへ保存する」という方法があります。
NSArray、NSDictionary、などのオブジェクトからプロパティリストへ出力する方法と、プロパティリストから読み込んだデータをオブジェクトに戻す方法について書きます。
1,オブジェクトからプロパティリストへ出力する方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//ここでは「data」というNSMutableArrayオブジェクトを
//プロパティリストとして出力するものとします
//保存先はDocumentsフォルダ、ファイル名はsettings.plistにします
id fileName = [[NSString alloc] initWithFormat:@"Documents/settings.plist"];
id path = [NSHomeDirectory() stringByAppendingPathComponent:fileName];
id plistData = [NSPropertyListSerialization
dataFromPropertyList:data
format:NSPropertyListXMLFormat_v1_0
errorDescription:nil];
if (plistData) {
[plistData writeToFile:path atomically:YES];
NSLog(@"NSData is saved at %@",path);
}else{
NSLog(@"NSData save error");
} |
2,プロパティリストから読み込んだデータをオブジェクトに戻す方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
//この例では「1」で出力した、
//Documentsフォルダにあるsettings.plistを読み込みます
NSPropertyListFormat format;
id fileName = [[[NSString alloc] initWithFormat:@"Documents/settings.plist"] autorelease];
id path = [NSHomeDirectory() stringByAppendingPathComponent:fileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
// ファイルが存在する
id xml = [[NSFileManager defaultManager] contentsAtPath:path];
id dic = [NSPropertyListSerialization propertyListFromData:xml
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:nil];
if (dic) {
//読み込みOK
//読み込まれたデータは「dic」というオブジェクトに入っています。
NSLog(@"settings.plist reading OK");
}else{
//読み込み失敗
NSLog(@"settings.plist reading error");
}
}else{
// ファイルが無い
NSLog(@"settings.plist no exist");
} |
Related posts: