Ios 保存plist文件不工作
我使用Xcode创建了一个文件,给他命名为file.plist,并另存为XML。现在,我使用以下代码读取和写入此文件:Ios 保存plist文件不工作,ios,objective-c,Ios,Objective C,我使用Xcode创建了一个文件,给他命名为file.plist,并另存为XML。现在,我使用以下代码读取和写入此文件: - (void)readPlist{ NSString *filePath = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"plist"]; NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithConten
- (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
为什么会发生这种情况以及如何解决此问题?iOS中的应用程序包是只读的
将您的plist文件放入应用程序的文档目录。您无法更改存储在应用程序主捆绑包中的文件。 您需要使用文档目录
// 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];