我可以将plist文件保存在Simulator中,但我无法将Plist文件保存在设备中。任何建议。
我正在使用
NSString* dictPath = [[NSBundle mainBundle] pathForResource:@"Dictionary" ofType:@"plist"];
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];
阅读文件
和
[dict writeToFile:dictPath atomically: YES];
写入文件。
答案 0 :(得分:12)
您无法写入主套装。您只能从主包中读取。如果要编写文件,则需要将其放入应用程序的文档目录中。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]];
如果您需要主捆绑中的plist,您可以先将其复制到文档目录,然后进行修改。建议进行检查以确保仅复制一次。
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);
}
答案 1 :(得分:1)
通常,您可以将它们存储在〜/ Documents或〜/ Library中,具体取决于文件。问题What is the documents directory (NSDocumentDirectory)?包括您需要了解的文档链接和示例代码。
答案 2 :(得分:1)
您需要将plist保存在Documents目录
中写
NSString *mainBundlePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dictPath = [mainBundlePath stringByAppendingPathComponent:@"Dictionary"];
NSDictionary * dict = ...; //Construct your dictionary
[dict writeToFile:dictPath atomically: YES];
阅读
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];