Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
908 views
in Technique[技术] by (71.8m points)

iphone - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...