将新输入附加到文档文件夹中的plist

时间:2014-04-04 01:01:13

标签: ios objective-c

经过大量搜索,我已经能够提出代码来纠正以前的失败。我想要完成的是接受来自UITextField的用户输入并将该输入添加到我的TableView,后者是从plist填充的。我的plist的根值是字典,我想保留它。我的问题是当writeToFile被调用时,我完全没有编写现有的值而不是插入,添加或附加到现有数据。我似乎没有尝试将两个词典组合起来,因为只有新值存储在plist中。关于我哪里出错的任何见解?我有以下代码

//////////********** Add New Cell When OK is Chosen

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

 UITextField *newDevice = [alertView textFieldAtIndex:0];
 NSLog(@"newDevice - %@",newDevice.text);

  if (alertView.tag == 1 && buttonIndex == 1){

 NSMutableDictionary *input = [[NSMutableDictionary alloc]init];
[input setObject:[NSArray arrayWithObject:newDevice.text] forKey:@"Room"];


 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Test.plist"];
 NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; 

 // Combine the two Dictionaries to create one
[dictionary addEntriesFromDictionary:input];

 // Write Combined Dictionary to plist
[dictionary writeToFile:path atomically:YES];

 // Add Newly Created text to Table because reload table doesn't do it
[myTableData addObject:newDevice.text];

 // Reload Table Data even though it seems useless 
[myTable reloadData];


    }

}

1 个答案:

答案 0 :(得分:0)

我猜你覆盖了密钥Room的值。

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Test.plist"];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

// Get exist input from plist
NSMutableArray *inputFromPlist = dictionary[@"Room"];
// add new object to input
[inputFromPlist addObject:newDevice.text];
// set Room with modified object
[dictionary setObject:inputFromPlist forKey:@"Room"];
// Write Combined Dictionary to plist
[dictionary writeToFile:path atomically:YES];
// do something after saving plist ...