我无法在我的 plist 文件中编写新字典,每次用户填写表格时我都想在其中保存数据。我现在使用的代码只覆盖数据,并没有按需要保存以前的字典。
这里的代码:
//////////// Save data into plist /////////////////
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];
// set the variables to the values in the text fields
self.titlestring = titleexperiencia.text;
self.descriptionstring = descriptionexperiencia.text;
self.coordinadastring = [self deviceLocation];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: titlestring, descriptionstring,coordinadastring, nil] forKeys:[NSArray arrayWithObjects: @"Title", @"Description", @"Coordinate", nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[plistData writeToFile:plistPath atomically:YES];
NSLog(@"Saved in Data Plist");
}
else
{
NSLog(@"Error in saveData: %@", error);
[error release];
}
我也尝试使用 AddObject: 而不是 writeToFile: 但这会使 App 崩溃。