使用Core Data一对多关系从JSON数组填充sqlite数据库

时间:2013-02-26 02:26:52

标签: json sqlite core-data

我正在尝试从JSON文件中读取数据并将其存储到sqlite中。我正在通过“简单”数据,但我无法弄清楚如何将我的数组中的一对多关系项转换为sqlite。

这是我的数据模型:

(抱歉 - 他们不允许我在这里进行屏幕截图...所以这里是数据模型的描述:)

    Entity: SeasonInfo 
    Attributes:
    year
    coach
    wins
    losses
    ties
        Relationship: players
        Destination: PlayerInfo
        Inverse seasonInfo

    Entity: PlayerInfo
    Attributes:
    name
    number
       Relationship: seasonInfo
       Destination: SeasonInfo
       Inverse: players

这是我的JSON:

    [
       { "year": 2012, "wins": 8,  "losses": 8, "ties": 0, "coach": "Garrett",
          "players": [ { "name": "Tony Romo",  "number": 9},
                      { "name": "Dez Bryant",   "number": 88} ],
       },
       { "year": 2011, "wins": 8,  "losses": 8, "ties": 0, "coach": "Garrett",
         "players": [ { "name": "DeMarcu Ware",  "number": 94},
                       { "name": "Felix Jones ",  "number": 28},
                       { "name": "Miles Austin",  "number": 19} ],
        },
        { "year": 2010, "wins": 6,  "losses": 10, "ties": 0, "coach": "Garrett/Phillips",
          "players": [ { "name": "Sean Lee",      "number": 50},
                       { "name": "Jason Witten",  "number": 82} ],
        }
     ]

这是我的代码:

    // Load JSON data into Array
    NSError* err = nil;
    NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"CowboySeason" ofType:@"json"];
    NSArray* cowboySeasonsArray = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
                                                                  options:kNilOptions
                                                                    error:&err];
    NSLog(@"Imported Seasons: %@", cowboySeasonsArray);


    // Export data from the array into the database

    // Store the SeasonInfo 
    [cowboySeasonsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        SeasonInfo *seasonInfo = [NSEntityDescription
                                          insertNewObjectForEntityForName:@"SeasonInfo"
                                          inManagedObjectContext:context];

        seasonInfo.year = [obj objectForKey:@"year"];
        seasonInfo.wins = [obj objectForKey:@"wins"];
        seasonInfo.losses = [obj objectForKey:@"losses"];
        seasonInfo.ties = [obj objectForKey:@"ties"];
        seasonInfo.coach = [obj objectForKey:@"coach"];

        seasonInfo.players = [obj objectForKey:@"players"];

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

cowboySeasonArray在日志中看起来像这样:

    2013-02-25 20:39:05.025 SeasonTestLoader[369:503] Imported Seasons: (
    {
    coach = Garrett;
    losses = 8;
    players =         (
                    {
            name = "Tony Romo";
            number = 9;
        },
                    {
            name = "Dez Bryant";
            number = 88;
        }
    );
    ties = 0;
    wins = 8;
    year = 2012;
},
    {
    coach = Garrett;
    losses = 8;
    players =         (
                    {
            name = "DeMarcu Ware";
            number = 94;
        },
                    {
            name = "Felix Jones ";
            number = 28;
        },
                    {
            name = "Miles Austin";
            number = 19;
        }
    );
    ties = 0;
    wins = 8;
    year = 2011;
},
    {
    coach = "Garrett/Phillips";
    losses = 10;
    players =         (
                    {
            name = "Sean Lee";
            number = 50;
        },
                    {
            name = "Jason Witten";
            number = 82;
        }
    );
    ties = 0;
    wins = 6;
    year = 2010;
}

所以它看起来像JSON解析器工作......但我无法弄清楚如何将一对多的PlayerInfo转换为sqlite。

我知道seasonInfo.players = [obj objectForKey:@“players”];行是错的......只是不知道该怎么做。

温柔......我是一个iOS新手。

1 个答案:

答案 0 :(得分:2)

看起来你已经拥有了团队工作的“外循环”,现在你只需要为每个团队添加一个“内循环”的玩家。

从创建团队的代码开始,在循环中开始:

// Other stuff from your code here, omitted for brevity
seasonInfo.ties = [obj objectForKey:@"ties"];
seasonInfo.coach = [obj objectForKey:@"coach"];

// Loop through each player, creating a new PlayerInfo entity for each one:
NSArray *playerArray = [obj objectForKey:@"players"]
[playerArray enumerateObjectsUsingBlock:^(id playerObj, NSUInteger playerIdx, BOOL *playerStop) {
    PlayerInfo *playerInfo = [NSEntityDescription
                                      insertNewObjectForEntityForName:@"PlayerInfo"
                                      inManagedObjectContext:context];

    playerInfo.seasonInfo = seasonInfo;
    playerInfo.name = [playerObj objectForKey:@"name"];
    playerInfo.number = [playerObj objectForKey:@"number"];
}];

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

因为您在PlayerInfo和SeasonInfo之间设置了反向关系,所以您可以从关系的任一端建立连接,另一端将自动处理。在这种情况下,您将创建新的PlayerInfo实体,并通过设置每个实体的seasonInfo值,将填充SeasonInfo侧的一对多关系。

您还可以将单个PlayerInfo对象添加到SeasonInfo的玩家关系集中,但我发现更加混乱的是,只需将多个实体中的关系添加回一个实体。