繁体   English   中英

从JSON到核心数据的预填充其他实体

[英]JSON to Core Data Pre Populating additional entities

我设法通过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]);
        }
    }];

将不胜感激。 谢谢

可可提供了一种使这一过程变得简单得多的方法。 多亏了键值编码,NSObject中有一个方法可以将上述内容简化为一行

[myObj setValuesForKeysWithDictionary:jsonDict];

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM