ios - RestKit:连接多对多关系

标签 ios objective-c core-data restkit restkit-0.20

我的应用程序具有以下核心数据模型:

+--------------------+         +-------------+
| Ingredient         |         | Dish        |
+--------------------+         +-------------+
| id                 |         | id          |
| title              |         | title       |
| dishId (transient) |
+--------------------+         +-------------+
| dishes             | <<--->> | ingredients |
+--------------------+         +-------------+

我还有一个网络服务,它允许我像这样请求给定菜肴的所有配料:

/dish/1/ingredients

(其中 1 是一些菜品 ID)。

对此类响应的要求如下:

{
    { "id": "1", "title": "milk" },
    { "id": "2", "title": "egg" },
    { "id": "3", "title": "flour" }
}

我读过有关 RKConnectionDescription 的信息,但我不知道如何在这种特殊情况下使用它来连接这两个实体。

这是我目前得到的映射:

RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:@"Ingredient" inManagedObjectStore:store];

[mapping setIdentificationAttributes:@[@"id"]];

[mapping addAttributeMappingsFromDictionary:@{
        @"id" : @"id",
        @"title" : @"title",
        @"@metadata.dishId" : @"dishId"
}];

更新

我向我的 Ingredient 实体添加了一个新的 transient 属性 dishId 并尝试像这样建立连接:

NSEntityDescription *entityDescription =
        [NSEntityDescription entityForName:@"Ingredient" inManagedObjectContext:mainContext];
NSRelationshipDescription *relationship =
        [entityDescription relationshipsByName][@"dishes"];
RKConnectionDescription *connection =
        [[RKConnectionDescription alloc] initWithRelationship:relationship attributes:@{
                @"dishId" : @"id"
        }];

[mapping addConnection:connection];

但是每次我请求另一道菜的配料时,它都会用新的连接替换旧的连接,所以我基本上得到了一对一的关系。例如,我首先请求煎蛋的配料,它将煎蛋与鸡蛋、牛奶和面粉联系起来。然后我请求煎饼的配料,它将煎饼与鸡蛋、牛奶和面粉联系起来,但是煎蛋卷与这些配料的联系丢失了。

assignmentPolicyRKConnectionDescription 上不可用。

最佳答案

您想使用 RKRoute创建请求路径并为您提供所需的关系映射(您不需要自己做)。您需要将路由的路径模式设置为 /dish/:id/ingredients,以便从 Dish 中提取身份并注入(inject)。

使用 routeWithRelationshipName:objectClass:pathPattern:method: 创建路由。

使用 getObjectsAtPathForRelationship:ofObject:parameters:success:failure: 获取内容。

一旦您连接了路由,它所做的任何映射都将与 URL 内容元数据一起提供。所以,在你的映射中你使用:

@"@metadata.routing.parameters.id" : @"dishId"

请注意,dishId 是添加到您在外键映射 (RKConnectionDescription) 中使用的 Ingredient 的新 transient 属性。

关于ios - RestKit:连接多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22796868/

相关文章:

iphone - 核心数据和运行时键值编码

ios - 用苹果智能 watch 检测反射

iphone - 如何将 NSDictionary 存储为核心数据中的可转换属性

ios - UIFont 自定义字体未在设备上显示

ios - 以编程方式编辑通讯簿的名字和姓氏

swift - CoreData/TableView - 'subscript' 的使用不明确

android - 查找 ios 和 android 的无效推送 token

ios - 如何获取动态创建的标签的对象 ID?

ios - 需要有关 Objective-C 中二进制搜索树实现的指导

ios - 核心数据反向排序关系获取