每当我保存数据时,我都有一个代码将数据添加到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.personName = nameEntered.text;
self.phoneNumbers = [[NSMutableArray alloc] initWithCapacity:3];
[phoneNumbers addObject:homePhone.text];
[phoneNumbers addObject:workPhone.text];
[phoneNumbers addObject:cellPhone.text];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: personName, phoneNumbers, nil] forKeys:[NSArray arrayWithObjects: @"Name", @"Phones", 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];
}
else
{
NSLog(@"Error in saveData: %@", error);
[error release];
}
答案 0 :(得分:1)
每次都使用新数据覆盖plist文件。如果要附加,则需要先从plist文件加载现有数据,然后将新数据添加到该字典中,然后写出更新后的字典。
答案 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写入文件。
希望有所帮助!