我正在使用下面的代码将一个新数组添加到plist中,但每次我在我的应用程序中添加一个带有textfield的新数组时,它会覆盖旧数组,即使它有一个全新的键。任何想法?
- (IBAction)saveViewerItems
{
// 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.data = [[NSMutableArray alloc] initWithCapacity:20];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: data, nil] forKeys:[NSArray arrayWithObjects: (@"%@", text), 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];
}
}
答案 0 :(得分:3)
要在文件中获取字典,请使用:
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:(NSString *)filePath];
要在该字典中编写另一个数组(使用不同的键),请使用:
[dictionary setObject:(id)myArray forKey:(NSString *)myKey];
要回写文件,请使用:
[dictionary writeToFile:(NSString *)filePath atomically:YES];
无需使用NSData
课程。有关详细信息,请查看Apple NSDictionary Class
答案 1 :(得分:1)
试试这个
// 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"];
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:plistPath] mutableCopy];
// set the variables to the values in the text fields
self.data = [[NSMutableArray alloc] initWithCapacity:20];
[plist setObject:[NSArray arrayWithObjects: data, nil] forKey:forKeys:[NSArray arrayWithObjects: (@"%@", text)];
[plist writeToFile:path atomically:YES];
[plist release];