无法保存plist ios

Maa*_*oyy 0 save plist ios

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

我正在使用

NSString* dictPath = [[NSBundle mainBundle] pathForResource:@"Dictionary" ofType:@"plist"];
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];
Run Code Online (Sandbox Code Playgroud)

阅读文件

[dict writeToFile:dictPath atomically: YES];
Run Code Online (Sandbox Code Playgroud)

写入文件.

Maa*_*oyy 12

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

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

如果您需要主捆绑中的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);
}
Run Code Online (Sandbox Code Playgroud)