unable to save plist ios

前端 未结 3 1363
慢半拍i
慢半拍i 2021-01-26 13:53

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 = [[NSB         


        
相关标签:
3条回答
  • 2021-01-26 14:05

    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];
    
    0 讨论(0)
  • 2021-01-26 14:10

    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);
    }
    
    0 讨论(0)
  • 2021-01-26 14:10

    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.

    0 讨论(0)
提交回复
热议问题