mkr*_*ral 4 iphone core-data one-to-many relationships ios
根据Ray Wenderlich的新教程,我能够获取JSON数据并将其存储到Core数据中.我很难理解如何使用Core Data中的关系来做到这一点.
这是我的数据模型:

这是我的JSON:
{
"results": [
{
"name": "Trivia 1",
"objectId": "1000",
"createdAt": "2012-08-31 18:02:52.249 +0000",
"updatedAt": "2012-08-31 18:02:52.249 +0000",
"questions": [
{
"text": "Question 1"
},
{
"text": "Question 2"
},
{
"text": "Question 3"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
最后,我在这里设置了managedObject的值:
//Sets values for ManagedObject, also checks type
- (void)setValue:(id)value forKey:(NSString *)key forManagedObject:(NSManagedObject *)managedObject {
NSLog(@"TYPE: %@", [value class]);
//If managedObject key is "createdAt" or "updatedAt" format the date string to an nsdate
if ([key isEqualToString:@"createdAt"] || [key isEqualToString:@"updatedAt"]) {
NSDate *date = [self dateUsingStringFromAPI:value];
//Set date object to managedObject
[managedObject setValue:date forKey:key];
} else if ([value isKindOfClass:[NSArray class]]) { //<---This would be the array for the Relationship
//TODO: If it's a Dictionary/Array add logic here
for(NSDictionary *dict in value){
NSLog(@"QUESTION");
}
} else {
//Set managedObject's key to string
[managedObject setValue:value forKey:key];
}
}
Run Code Online (Sandbox Code Playgroud)
我已经看过这个问题,但我真的很困惑如何从Ray Wenderlich示例中将各个部分连接在一起.任何帮助将不胜感激.
在你的for循环中你将要做一些特殊的handeling,如果你正在处理一个QuestionGroup,你会知道该对象上的数组是问题(假设它是唯一的数组),所以你可以为每个创建一个新的Question对象.在词典中输入.这将破坏同步引擎的通用性,但如果需要,您可以通过一些额外的步骤重新获得它.
else if ([value isKindOfClass:[NSArray class]]) {
if ([[managedObject entity] name] isEqualToString:@"QuestionGroup") {
NSSet *questions = [NSMutableSet set];
for (NSDictionary *question in value) {
// create your question object/record
NSManagedObject *questionManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Question" inManagedObjectContext:managedObjectContext];
// setup your question object
questionManagedObject.text = [question valueForKey:@"text"];
// store all the created question objects in a set
[questions addObject:questionManagedObject];
}
// assign the set of questions to the relationship on QuestionGroup
[managedObject setValue:questions forKey:@"questions"];
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3884 次 |
| 最近记录: |