我想從JSON文件中讀取數據並將其存儲到sqlite中。我正在通過「簡單」數據,但我無法弄清楚如何從我的數組中獲取一對多關係項目到sqlite中。從核心數據一對多關係JSON數組填充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新手。
真棒!這很好。謝謝您的幫助。 – 2013-02-26 04:47:50