简体   繁体   中英

How can I write to a plist file?

I wrote this small bit of code to write to a plist file. I am not getting any errors or warnings from XCode, so I am really lost. "Root" is not defined in this code section, but it is just a dictionary of the data that I pulled from the plist.

Does anyone have an idea of why this would not write to a plist file? It literally does not change the file at all.

    NSMutableArray *newReports = [[NSMutableArray alloc] init];
    newReports = [[Root objectForKey:@"Reports"] mutableCopy ];

    //Creating data model for new report
    NSMutableDictionary *newReport = [[NSMutableDictionary alloc] init];

    NSString *tempTitle = titleField.text;
    NSString *tempEmployee = employeeField.text;
    NSArray *tempNodes = [[NSArray alloc] init];

    [newReport setObject:tempTitle forKey:@"Title"];
    [newReport setObject:tempEmployee forKey:@"Employee"];
    [newReport setObject:tempNodes forKey:@"Nodes"];

    [newReports addObject:newReport];

    NSMutableDictionary *newRoot = [[NSMutableDictionary alloc] init];

    [newRoot setObject:newReports forKey:@"Reports"];

    //Writing data to plist
    NSString *Path = [[NSBundle mainBundle] bundlePath];
    NSString *filePath = [Path stringByAppendingPathComponent:@"data.plist"];

    [newRoot writeToFile:filePath atomically: YES];

Thanks for the help!

try constructing your file path like this

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath 
                         stringByAppendingPathComponent:@"data.plist"];
[newRoot writeToFile:filePath atomically: YES]; 

If you're running this on a device, the main bundle is read only. You'll need to write this plist into the user's documents directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM