0

我已经设法通过 JSON 文件预先填充了一个核心数据模型,该模型由一个具有许多属性的实体组成。

然后我添加了第二个实体,并在使用相同的 JSON 文件预填充这个实体时遇到了问题,所以我想我会创建另一个 JSON 文件来预填充第二个实体,但这似乎不起作用。

下面的代码是我尝试使用的:

    //Below is the code for the first entity

    NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"Exercises" ofType:@"json"];
    NSArray* Exercises = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
                                                         options:kNilOptions
                                                           error:&err];
    NSLog(@"Imported Exercises: %@", Exercises);

    [Exercises enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        Exercise *exercise = [NSEntityDescription
                              insertNewObjectForEntityForName:@"Exercise"
                              inManagedObjectContext:context];
        exercise.tag = [obj objectForKey:@"tag"];
        exercise.name = [obj objectForKey:@"name"];
        exercise.type = [obj objectForKey:@"type"];    
       NSError *error;
        if (![context save:&error]) {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }
    }];







//Below is the code for the second Entity


    dataPath = [[NSBundle mainBundle] pathForResource:@"Weights" ofType:@"json"];



    //Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
    NSArray* Weights = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
                                                         options:kNilOptions
                                                           error:&err];
    NSLog(@"Imported Weights: %@", Weights);

    [Weights enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        Weight *weight = [NSEntityDescription
                      insertNewObjectForEntityForName:@"Weight"
                      inManagedObjectContext:context];
        weight.weight = [obj objectForKey:@"weightEntry"];

        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }
    }];

将不胜感激任何帮助。谢谢你

4

1 回答 1

0

Cocoa 提供了一种方法,使这变得非常简单。由于键值编码,在 NSObject 中有一个方法可以将上面的内容减少到一行

[myObj setValuesForKeysWithDictionary:jsonDict];

这将通过 jsonDict 中的键/值对运行,并在 myObj 上设置相同的键/值对

于 2013-08-13T22:38:22.387 回答