我使用Xcode创建了一个文件,并将其命名为file.plist,然后另存为XML。现在要读写这个文件,我使用以下代码:
- (void)readPlist{
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSString *value;
value = [plistDict objectForKey:@"Name"];
NSLog(@"%@",value);
}
- (void)writeToPlist
{
NSLog(@"Data is Writing... ");
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
[plistDict setValue:@"StackOverflow" forKey:@"Name"];
[plistDict writeToFile:filePath atomically: YES];
}
这段代码运行得很好,也很简单,但我有一个问题,在viewDidLoad中我执行以下命令:
- (void)viewDidLoad {
[super viewDidLoad];
[self readPlist];
[self writeToPlist];
[self readPlist];
}
输出为:
Hello World
Data is Writing...
StackOverflow
太好了,现在让我们重新构建并运行我的应用程序。。。。并且输出是相同的!字符串Hello World继续出现,正确的输出应该是:
StackOverflow
Data is Writing...
StackOverflow
为什么会发生这种情况,以及如何解决这个问题?
您不能更改存储在应用程序主捆绑包中的文件。您需要使用文档目录。
// Get the plist from the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"File.plist"];
NSMutableArray *content = [NSMutableArray arrayWithContentsOfFile:path];
// Save plist
[content writeToFile:path atomically: YES];
iOS中的应用程序捆绑包是只读的。
将您的plist文件放入应用程序的文档目录中。