IOS在plist中创建字典列表

时间:2012-08-07 12:13:35

标签: ios plist

我在我的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:但这会导致应用程序崩溃。

2 个答案:

答案 0 :(得分:0)

好吧,崩溃可能是由于你过度释放错误变量而造成的。

答案 1 :(得分:0)

阅读plistPath的内容:
    NSMutableData * myData = [NSMutableData dataWithContentsOfFile:plistPath];
并改变这一点:

// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];  

到:

// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];  
[myData appdendData:plistData];    

最后将myData写入文件。

希望有所帮助!