如何写入plist文件?

时间:2010-11-07 02:03:40

标签: iphone objective-c xcode

我写了一小段代码来写一个plist文件。我没有从XCode收到任何错误或警告,所以我真的迷路了。 “Root”未在此代码部分中定义,但它只是我从plist中提取的数据的字典。

有没有人知道为什么这不会写入plist文件?它根本不会改变文件。

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:5)

尝试像这样构建文件路径

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

答案 1 :(得分:4)

如果您在设备上运行此功能,则主捆绑包是只读的。您需要将此plist写入用户的文档目录。