0

我已经使用 plist 文件来存储我的数据,它确实适用于读取和写入数据。现在如何删除我的 iPhone 设备中的旧 SaveData.plist 文件?因为当我从 xcode 中删除它并添加新的同名文件(SaveData.plist)并在我的设备中运行它时,我的旧数据仍在里面。

我使用此代码添加我的 SaveData.plist

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"SaveData.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@"SaveData" ofType:@"plist"];
    [fileManager copyItemAtPath:bundle toPath: path error:&error];
}
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

谢谢你。

4

1 回答 1

1

如果有旧版本,if语句(如果文件已经存在):

if (![fileManager fileExistsAtPath: path])

导致它不会被复制到文档文件夹中。

您可以先删除文档文件夹中的文件:

if ([fileManager removeItemAtPath:path error:&error] == YES)
{
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@"SaveData" ofType:@"plist"];
    [fileManager copyItemAtPath:bundle toPath: path error:&error];
}

您也可以考虑先加载旧文件的内容,以便迁移保存的数据。

于 2012-07-26T06:18:57.070 回答