您好,我正在尝试使用电话号码创建字典,我可以填充字典并将其添加到 plist 但是当我尝试再次添加到 plist 时,我会覆盖文件。
#import "FirstViewController.h"
@interface FirstViewController ()
{
NSMutableDictionary *NameNumberDict;
NSDictionary *plistDict;
NSMutableArray *numberArray;
NSString *filePath;
}
@end
@implementation FirstViewController
@synthesize NameTxtField;
@synthesize FirstNumField;
@synthesize SecNumField;
@synthesize personName;
@synthesize phoneNumbers;
- (void)viewDidLoad
{
[super viewDidLoad];
//get some memory
plistDict = [[NSDictionary alloc]init];
NameNumberDict = [[NSMutableDictionary alloc]init];
//make a file path string
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [pathArray objectAtIndex:0];
filePath = [path stringByAppendingPathComponent:@"data.plist"];
NSFileManager *manager = [NSFileManager defaultManager];
// here i set the Dictionary to the file
//give the file to my dictonary
NameNumberDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSLog(@"The count: %i", [NameNumberDict count]);
//make sure the file is there
NSString *err = nil;
NSData *plist;
plist = [NSPropertyListSerialization dataFromPropertyList:NameNumberDict format:NSPropertyListBinaryFormat_v1_0 errorDescription:&err];
if([manager fileExistsAtPath:@"data.plist"] == NO)
{
[manager createFileAtPath:[NSString stringWithFormat:@"data.plist"] contents:plist attributes:nil];
}
}
- (void)viewDidUnload
{
[self setNameTxtField:nil];
[self setFirstNumField:nil];
[self setSecNumField:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
// Populate the dictionary when they dismiss the keyboard if all the data is filled out
-(IBAction)TextFieldReturn:(id)TextField
{
if(!NameTxtField.text && !FirstNumField.text && !SecNumField.text);
{
NSString *name = NameTxtField.text;
numberArray = [[NSMutableArray alloc]init];
[numberArray addObject:FirstNumField.text];
[numberArray addObject:SecNumField.text];
[NameNumberDict setObject:name forKey:@"Name"];
[NameNumberDict setObject:numberArray forKey:@"Number"];
NSLog(@"dicSave: %@",NameNumberDict);
}
[TextField resignFirstResponder];
}
// and down here is where im lost Im not sure how to append the data to the Dictionary and write it to file
- (IBAction)AddBtn:(UIButton *)sender
{
plistDict = [[NSMutableDictionary alloc]initWithDictionary:NameNumberDict];
[plistDict writeToFile:filePath atomically:YES];
NSLog (@"File %@ exists on iPhone",filePath);
}
@end