【问题标题】:populating core data through JSON receiving null entries通过接收空条目的 JSON 填充核心数据
【发布时间】:2013-08-14 20:39:27
【问题描述】:

尝试使用 JSON 填充核心数据结构,

代码如下?

    NSManagedObjectContext *context = managedObjectContext();
    // Save the managed object context
    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
        exit(1);
    }

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


    NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:context];
    NSString *theJSONString = @"{\"key\":\"value\"}";
    NSError *theError = NULL;
    NSDictionary *jsonDict = [NSDictionary dictionaryWithJSONString:theJSONString error:&theError];

    Exercise *exercise = [NSEntityDescription insertNewObjectForEntityForName:@"Exercise"
                                                       inManagedObjectContext:context];

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

        NSDictionary *attributes = [[object entity] attributesByName];
        for (NSString *attribute in attributes) {
            id value = [jsonDict objectForKey:attribute];
            if (value == nil) {
                continue;
            }
            [exercise setValue:value forKey:attribute];
        }
        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }
    }];

代码编译,分析创建的sqlite数据库后,所有属性都填充了空值。

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


    [weightsFromJSON enumerateObjectsUsingBlock:^(NSDictionary *weightDictionary, NSUInteger idx, BOOL *stop) {

        Weight *weight = [NSEntityDescription insertNewObjectForEntityForName:@"Weight"
                                                           inManagedObjectContext:context];
        NSDictionary *attributes = [[weight entity] attributesByName];
        for (NSString *attribute in [attributes allKeys]) {
            id value = [weightDictionary objectForKey:attribute];
            if (value == nil) {
                continue;
            }
            [weight setValue:value forKey:attribute];
        }
        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }
    }];

为第二个实体编辑了上面的代码,但未能说明数据参数是 hill

【问题讨论】:

    标签: ios xcode json core-data


    【解决方案1】:

    您正在枚举从磁盘上您放入Exercises 的 JSON 数据加载的每个对象(顺便说一句,不要将局部变量的名称大写),但是您没有使用这些对象作为数据源,而是使用jsonDict,它是从字符串硬编码的,并且只有一个键/值对。换行试试

    id value = [jsonDict objectForKey:attribute];
    

    改为:

    id value = [(NSDictionary *)obj objectForKey:attribute];
    

    这实际上应该应用您加载的数据。但是,您的代码中还有其他问题 - 您只插入一个实体,而不是为 Exercises 中的每个元素插入一个实体,以及插入一个您分配给 object 的无关实体。下面是一些我认为可以做你想做的事情的代码:

    NSError* err = nil;
    NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"exercisesFromJSON" ofType:@"json"];
    NSArray* exercisesFromJSON = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
                                                         options:kNilOptions
                                                          error:&err];
    NSLog(@"Imported exercisesFromJSON: %@", exercisesFromJSON);
    
    
    [exercisesFromJSON enumerateObjectsUsingBlock:^(NSDictionary exerciseDictionary, NSUInteger idx, BOOL *stop) {
        Exercise *exercise = [NSEntityDescription insertNewObjectForEntityForName:@"Exercise"
                                                       inManagedObjectContext:context];
        NSDictionary *attributes = [[exercise entity] attributesByName];
        for (NSString *attribute in [attributes allKeys]) {
            id value = [exerciseDictionary objectForKey:attribute];
            if (value == nil) {
                continue;
            }
            [exercise setValue:value forKey:attribute];
        }
        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }
    }];
    

    【讨论】:

    • 谢谢,它并没有填充数据......我的 JSON 文件有两个条目,在更改这一行后,代码设法将第二个(最后一个)条目数据输入到核心数据结构中,但第一个条目数据仍设置为 null...
    • @user2512523 我重新阅读了您的代码并注意到了许多其他问题,它们可能是其中的一部分。
    • 完美运行。非常感谢,已经为此工作了3天。如果您不介意,请快速提问,如果我要在同一个核心数据模型中使用第二个 JSON 文件填充第二个实体,...我会复制您提供的更改实体名称的代码吗?
    • 更改实体名称、您加载的 JSON 文件以及 exercise 变量的类型和名称,这应该可以工作。此外,我认为您不必多次保存托管对象上下文。也许在整个导入结束时保存。
    • 谢谢我已经添加了第二个实体代码,但是收到一个数据参数是 nil 异常,我将代码添加到上面的原始问题中,如果你不介意看看它。我确实认为可能是第二个 json 文件不正确,但那里一切似乎都很好:S
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2016-10-25
    • 2021-10-16
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多