无法保存plist ios [英] unable to save plist ios

查看:212
本文介绍了无法保存plist ios的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够将plist文件保存在Simulator中,但我无法将Plist文件保存在设备中。任何建议。

I m able to save the plist file in Simulator but I m not able to save the Plist file in the device. Any suggestion.

我正在使用

NSString* dictPath = [[NSBundle mainBundle] pathForResource:@"Dictionary" ofType:@"plist"];
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];

阅读文件

[dict writeToFile:dictPath atomically: YES];

写入文件。

推荐答案

您无法写入主包。您只能从主包中读取。如果要编写文件,则需要将其放入应用程序的文档目录中。

You can not write in to main bundle. You only can read from main bundle. If you want to write an file you need to place it in to the documents directory of your app.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]]; 

如果您需要主捆绑中的plist,您可以先将其复制到文档目录然后修改它。建议检查以确保只复制一次。

If you need the plist from the main bundle you can copy it first in to the documents directory then modify it. It is advised to have a check to ensure it is copied only once.

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]]; 

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path]){
    NSLog(@"File don't exists at path %@", path);

    NSString *plistPathBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];

    [fileManager copyItemAtPath:plistPathBundle toPath: path error:&error]; 
}else{
    NSLog(@"File exists at path:%@", path);
}

这篇关于无法保存plist ios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆