Property Listをつかってみよう -6
Property Listをつかってみよう -5 - Macアプリつくるブログ
からのつづきです。
さて、あとはデータを読み書きするコードを書くのみです。
まず、Property Listに入っているデータを書き出すコードは、
- (id) init {
self = [super init];
if (self) {
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:@"Data.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
}
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
if (!temp) {
NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
}
self.personName = [temp objectForKey:@"Name"];
self.phoneNumbers = [NSMutableArray arrayWithArray:[temp objectForKey:@"Phones"]];
}
return self;
}
これをController.mに追記します。
(どこに書くという指示は元記事にはありませんが、
とりあえず動くのを目標とするためここにしておきます。)
また、アプリを閉じたときに変更を反映するコードは、
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
NSString *error;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:@"Data.plist"];
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects:
[NSArray arrayWithObjects: personName, phoneNumbers, nil]
forKeys:[NSArray arrayWithObjects: @"Name", @"Phones", nil]];
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
if(plistData) {
[plistData writeToFile:plistPath atomically:YES];
}
else {
NSLog(error);
[error release];
}
return NSTerminateNow;
}
で、これもController.mに追記しましょう。
あとは、"Run"をおして、実行してみてください。
Property Listの値が反映されたWindowが出ましたか??
値をダブルクリックして、終了(Command+Q)して、また開くと??
一旦このチュートリアルは終わりです。
ありがとうございました、これからも頑張りましょう!^^