我在绘制一个特定案例时遇到了困难 这与here
完全相同product:{
"id": 123,
"name": "Produce RestKit Sample Code",
"description": "We need more sample code!",
"tasks": [
{"name": "Identify samples to write", "assigned_user_id":1},
{"name": "Write the code", "assigned_user_id": 1},
{"name": "Push to Github", "assigned_user_id": 1},
{"name": "Update the mailing list", "assigned_user_id": 1}]
}
所以我为任务对象创建了映射。 我为产品对象创建了与NSSET任务的关系。
但现在每次解析新数据时,核心数据中的任务都会重复。 (正常原因没有ID)
拖车解决方案:
我不知道如何实施任何此解决方案。任何帮助都会很棒。
答案 0 :(得分:1)
我不太确定如何映射此任务对象,但我通过以下方式解析NSData
和JSON字符串:
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
在这种情况下,我得到一个带有一个键“{product”的NSDictionary
,该键的对象是另一个字典。具有“任务”键的NSDictionary
对象是四个NSArray
个对象的NSDictionary
。
现在,JSON摘录不是有效的JSON,但我认为它只是更广泛的JSON文件的一个叶子。但是出于测试目的,让我们假设JSON文件如下:
{
"product" : {
"id": 123,
"name": "Produce RestKit Sample Code",
"description": "We need more sample code!",
"tasks": [
{"name": "Identify samples to write", "assigned_user_id": 1},
{"name": "Write the code", "assigned_user_id": 1},
{"name": "Push to Github", "assigned_user_id": 1},
{"name": "Update the mailing list", "assigned_user_id": 1}]
}
}
然后我可以解析那个JSON:
NSString *filename = [[NSBundle mainBundle] pathForResource:@"13628140" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filename];
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
NSDictionary *product = dictionary[@"product"];
NSArray *tasks = product[@"tasks"];
NSDictionary *firstTask = tasks[0];
NSString *firstName = firstTask[@"name"];
NSString *firstAssignedUserId = firstTask[@"assigned_user_id"];
或者,如果您想要枚举任务:
NSDictionary *product = dictionary[@"product"];
NSArray *tasks = product[@"tasks"];
[tasks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary *task = obj;
NSLog(@"Task \"%@\" is assigned to %@", task[@"name"], task[@"assigned_user_id"]);
}];
您是否只是询问如何将NSArray
tasks
存储在核心数据中?