我发出了一个获取带有嵌套数据数组的对象的请求。但是,RestKit仅保存嵌套数据数组中的最后一项。
例如,这是服务器正在发送的JSON响应
{
"nutrition_day": {
"id": "5342e9e13138610012420100",
"start_on": "2014-04-07",
"meal_goals": [
{
"id": "5342e9e13138610012410100",
"name": "Breakfast",
"food_entries": [
{
"id": "535429513663320008210000",
"consumed_on": "2014-04-20",
"food_id": 33801,
"serving_id": 29457,
}
]
},
{
"id": "5342e9e13138610012430100",
"name": "Morning Snack",
"food_entries": []
}
]
}
}
但是,使用下面的代码,当我尝试访问nutrition_data.meal_goals时,我只剩下数组中的最后一项“Morning Snack”而我没有得到“早餐”
映射:
+ (void)mapping
{
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
RKEntityMapping *responseMapping = [RKEntityMapping mappingForEntityForName:@"NutritionDay" inManagedObjectStore:[[RKObjectManager sharedManager] managedObjectStore]];
[requestMapping addAttributeMappingsFromArray:@[@"date"]];
[responseMapping addAttributeMappingsFromArray:@[@"start_on", @"protein_target"]];
[responseMapping setIdentificationAttributes:@[@"start_on"]];
[responseMapping addRelationshipMappingWithSourceKeyPath:@"meal_goals" mapping:[MealGoal responseMapping]];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping
objectClass:[NutritionDay class]
rootKeyPath:@"nutrition_day"
method:RKRequestMethodGET];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping
method:RKRequestMethodAny
pathPattern:@"nutrition/days/:date"
keyPath:@"nutrition_day"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addRequestDescriptor:requestDescriptor];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
}
请求:
[[RKObjectManager sharedManager] getObjectsAtPath:@"nutrition/days/2014-12-12" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NutritionDay *nut = ((NutritionDay *)mappingResult.firstObject);
NSLog(@"%lu", (long)nut.meal_goals.count); // this always returns 1 when it should be 2
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(@"fail");
}];
我是否需要做些什么来让RestKit识别整个关系并保存它?
答案 0 :(得分:2)
我建议您在映射中包含id
,并将其用作标识属性。
meal_goals
应该是一个多对多的关系(反向)。
您的日志应为:
NSLog(@"%lu", (long)nut.meal_goals.count);
除了那些东西,你展示的代码看起来是正确的。记录整个映射结果以验证内容。