unable to save plist ios

老子叫甜甜 提交于 2019-12-02 17:07:47

问题


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.

I m using

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

to read the files

and

[dict writeToFile:dictPath atomically: YES];

to write to file.


回答1:


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

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);
}



回答2:


Generally you would store these in ~/Documents or in ~/Library depending on the file. The question What is the documents directory (NSDocumentDirectory)? includes the documentation links and sample code you need to understand this.




回答3:


You need to save the plist in Documents directory

to write

NSString *mainBundlePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dictPath = [mainBundlePath stringByAppendingPathComponent:@"Dictionary"];
NSDictionary * dict = ...; //Construct your dictionary
[dict writeToFile:dictPath atomically: YES];

to read

NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];


来源:https://stackoverflow.com/questions/7355827/unable-to-save-plist-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!