如何使用其他json文件的值覆盖json文件? 我使用2个json文件来存储应用程序配置的数据,一个是应用程序的默认值,另一个是用户给出的自定义配置值,它将始终运行从中检索数据自定义文件,因此在用户想要恢复原始配置的情况下,它会获取默认文件的值并覆盖自定义文件,这就是逻辑,但我仍在尝试弄清楚如何覆盖文件。 / p>
以下是我在代码中尝试做的事情,但仍然没有写任何东西:
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"custom" ofType:@"json"];
// Retrieve local JSON file called custom.json
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error = nil; // This so that we can access the error if something goes wrong
NSData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
// Load the file into an NSData object called JSONData
NSDictionary *lista = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
NSNumber * test = [lista objectForKey:@"tempoTrabalho1"];
NSInteger teste = [test integerValue];
NSLog(@"%ld",(long)teste);
//file to copy from
NSString *json = [ [NSBundle mainBundle] pathForResource:@"example" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
@end
我想用example.json覆盖custom.json:
example.json:
{
"tempoTrabalho1": 25,
"tempoTrabalho2": 25,
"tempoTrabalho3": 25,
"tempoTrabalho4": 25,
"tempoDescanso1": 5,
"tempoDescanso2": 5,
"tempoDescanso3": 5,
"tempoDescanso4": 20
}
custom.json:
{
"tempoTrabalho1": 30,
"tempoTrabalho2": 30,
"tempoTrabalho3": 30,
"tempoTrabalho4": 30,
"tempoDescanso1": 10,
"tempoDescanso2": 10,
"tempoDescanso3": 10,
"tempoDescanso4": 30
}
答案 0 :(得分:1)
默认情况下会覆盖[NSData writeToFile:atomically:]
方法(您必须使用接受选项的方法版本并指定NSDataWritingWithoutOverwriting
才能不覆盖)。