IOS New array in plist with new key overwrites old array with different key
I am using the following bit of code to add a new array to the plist, but every time I add a new array with a textbox in my application, it overwrites the old one, even if it has a brand new key. any ideas?
- (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];
}
}
+3
source to share
2 answers
To get the diktat already in the file, use:
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:(NSString *)filePath];
To write another array in this dictionary (using a different key) use:
[dictionary setObject:(id)myArray forKey:(NSString *)myKey];
To write the file back, use:
[dictionary writeToFile:(NSString *)filePath atomically:YES];
There is no need to use a class NSData
. For more information check out Apple NSDictionary Class
+3
source to share
Try this
// 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];
+1
source to share