我在 iphone 应用程序中有一个视图控制器,它将键值对添加到 plist 文件中。然后它将整个 plist 显示在带有表格视图的视图控制器中。我遇到的问题是它只会显示 iPhone 模拟器中的值,并且如果我完全重新启动应用程序,它只会显示新的键值对。
注意:plist 文件应该添加到应用程序的资源目录更新:下面的代码是我的问题的解决方案,此外,为了查看 plist 中的新条目,我实现了一个刷新按钮,该按钮基本上在 viewDidLoad 中运行该部分.
添加键值对的视图控制器的代码如下:
- (IBAction)addAction:(UIBarButtonItem *)sender
{
NSString *myFile=[[NSBundle mainBundle] pathForResource:@"File" ofType:@"plist"];
dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:myFile];
NSArray *docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath=[docDir objectAtIndex:0];
NSString *plistPath=[filePath stringByAppendingPathComponent:@"File.plist"];
//Check plist's existance using FileManager
NSError *err=nil;
NSFileManager *fManager=[NSFileManager defaultManager];
if(![fManager fileExistsAtPath:plistPath])
{
//file doesn't exist, copy file from bundle to documents directory
NSString *bundlePath=[[NSBundle mainBundle] pathForResource:@"File" ofType:@"plist"];
[fManager copyItemAtPath:bundlePath toPath:plistPath error:&err];
}
//Get the dictionary from the plist's path
dictionary =[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
//Manipulate the dictionary
[dictionary setObject:textContent forKey:textName];
//Again save in doc directory.
[dictionary writeToFile:plistPath atomically:YES];
}
这是在另一个视图控制器的表视图中显示 plist 的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize table data
NSArray *docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath=[docDir objectAtIndex:0];
NSString *plistPath=[filePath stringByAppendingPathComponent:@"File.plist"];
dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:**plistPath**];
verses = [dictionary allKeys];
[self.mainTableView reloadData];
}
感谢你的帮助!