使用MagicalRecord从JSON保存父子关系

时间:2013-09-04 16:10:06

标签: objective-c core-data magicalrecord

我正在读取具有以下关系的本地JSON文件

Country -< Venues

JSON文件包含作为父项的所有国家/地区,然后根据以下示例包含作为子项的地点:

// Sample JSON (Countries have many venues)
    [{
        "id": 1,
        "name": "USA",
        "venues": [
            {
                "venue": "Von Braun Center",
                "city" : "Huntsville",
                "state": "Alabama",
                "capacity": 13760
            }
        ]
    }];

我遇到的问题是我想使用MagicalRecord保存实体和关系,但它一直在抱怨无效的上下文。

// Read through a JSON file then save to Core Data
        [MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *c) {
            Country *country = [Country createInContext:c];
            [country setName:name];
        } completion:^{

            for (NSDictionary *venueData in venues) {

                NSString *venue = (NSString *) [venueData objectForKey:@"venue"];
                NSString *city = (NSString *) [venueData objectForKey:@"city"];
                NSString *state = (NSString *) [venueData objectForKey:@"state"];

                Venue *v = [Venue createEntity];
                v.name = venue;
                v.city = city;
                v.state = state;
                v.country = country;

            } // next

            [[NSManagedObjectContext defaultContext] saveNestedContexts];
        }];

我需要首先保存country但我不能在第二部分使用它,我将地点设置为一个国家。

我的问题是:

  1. 如何在国家/地区对象之间使用MagicalRecord保存国家/地区并创建/保存关系

  2. 如何使我的国家/地区对象在完成块中工作。

  3. 非常感谢


    根据SO成员的建议,我已经能够通过将其放入一个区块来解决问题;

    for (NSDictionary *dict in json) {
                    NSString *name = (NSString *) [dict objectForKey:@"name"];
                    NSArray *venueList = (NSArray *) [dict valueForKey:@"venues"];
    
                    [MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *c) {
                        Country *country = [Country createInContext:c];
                        [country setName:name];
    
                        for (NSDictionary *venueData in venueList) {
    
                            NSString *name = (NSString *) [venueData objectForKey:@"venue"];
                            NSString *city = (NSString *) [venueData objectForKey:@"city"];
                            NSString *state = (NSString *) [venueData objectForKey:@"state"];
                            //NSNumber *capacity = (NSNumber *) [NSNumber numberWithInt:[[venueData valueForKey:@"capacity"] intValue]];
    
                            Venue *v = [Venue createInContext:c];
                            [v setName:name];
                            [v setCity:city];
                            [v setState:state];
                            [v setCountry:country];
                        } // next
    
                    } completion:^{
                    }];
                } // next
    

    非常感谢所有帮助过的人

1 个答案:

答案 0 :(得分:2)

只需在第一个保存区中执行所有操作,忘记完成块。在这种情况下只做一次保存就可以了,然后你不必担心在错误的环境中创建对象。