保存plist文件不起作用

时间:2015-11-22 21:06:03

标签: ios objective-c

我使用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

为什么会发生这种情况以及如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您无法更改存储在应用主程序包中的文件。 您需要使用文档目录。

// 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];

答案 1 :(得分:1)

iOS中的应用程序包是只读的。

将plist文件放入应用程序的文档目录中。