unable to save plist ios

前端 未结 3 1398
慢半拍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: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);
    }
    

提交回复
热议问题