plistから読み込んだデータを簡単にオブジェクトに変換する方法
plistからデータを読み込んでオブジェクト化する時はNSPropertyListSerialization propertyListWithData: options: format: error:を使うと便利。 例えばPerson.plistを作成したとする。 内容は下記のようになっている。
Person.plist
コード
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Person.plist" ofType:nil]; NSData *plistData = [NSData dataWithContentsOfFile:filePath]; NSPropertyListFormat format = NSPropertyListXMLFormat_v1_0; NSError *error; id persons = [NSPropertyListSerialization propertyListWithData:plistData options:(NSPropertyListReadOptions)NSPropertyListImmutable format:&format error:&error]; if (!persons) { return; } for (NSDictionary *person in persons) { NSLog(@"firstName:%@", person[@"firstName"]); NSLog(@"lastName:%@", person[@"lastName"]); NSLog(@"age:%@", person[@"age"]); } }
出力ログ
firstName:Ichiro
lastName:Suzuki
age:40
firstName:Keisuke
lastName:Honda
age:27
firstName:Ryosuke
lastName:Irie
age:23