【问题标题】:RestKit Router - How to implement routes with nested variables?RestKit 路由器 - 如何使用嵌套变量实现路由?
【发布时间】:2014-01-14 15:28:10
【问题描述】:

过去我为每个 RKResponseDescriptor 以及每个 RKObjectManager get/post/patch/delete 方法指定了路径参数。这可行,但似乎 RKRouter 是更好、更模块化的方式。

我无法设置包含嵌套变量的动态路由。例如:

添加路线

RKRoute *locationsRoute = [RKRoute routeWithClass:[Location class]     pathPattern:@"users/:userID/locations/:locationID" method:RKRequestMethodAny];
[[RKObjectManager sharedManager].router.routeSet addRoutes:@[locationsRoute]];

设置响应描述符

 RKResponseDescriptor *locationResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:locationResponseMapping
                                                                                          method:RKRequestMethodAny
                                                                                     pathPattern:nil
                                                                                         keyPath:nil
                                                                                     statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

调用对象管理器

[[RKObjectManager sharedManager] getObject:[Location class] path:nil parameters:nil success:nil failure:nil];

在使用路由器之前,我会在对象管理器调用路径中包含用户 ID。 (例如:path:[NSString stringWithFormat:@"users/%@/locations/%@", [self getCurrentUser].userID, location.locationID])。但是,在使用路由器时,我似乎无法弄清楚如何指定它。 这样做的正确方法是什么?我希望不必将用户 ID 硬编码到路由路径中。

重要的是要注意,我的所有映射都已正确设置,在尝试实施路线之前一切都完美无缺。任何帮助表示赞赏!

【问题讨论】:

    标签: ios objective-c restkit restkit-0.20 rkobjectmapping


    【解决方案1】:

    你的路线很好,这是错误的:

    [[RKObjectManager sharedManager] getObject:[Location class] ...
    

    因为您需要传递Location 类的实例(不是类对象),并且该实例需要设置userIDlocationID 属性,以便可以将它们注入到路由路径模式中。

    【讨论】:

    • 再次感谢,韦恩。对于索引调用,您没有要查找的特定记录怎么办?您是否创建任意 Location 对象只是为了传递用户 ID?
    • 在这种情况下,我通常会使用自定义对象或字典作为源对象(传递给路由器的类必须匹配)。或者干脆不使用路由器,使用最适合手头情况的路由器。
    【解决方案2】:

    记住 Wain 的回答,我最终需要为单个对象提供多个不同的路线;其索引是基于关系的路由。例如:

    索引

    RKRoute *locationIndexRoute = [RKRoute routeWithRelationshipName:@"locations" objectClass:[User class] pathPattern:@"users/:userID/locations" method:RKRequestMethodGET];
    
    [[RKObjectManager sharedManager] getObjectsAtPathForRelationship:@"locations" ofObject:[self getCurrentUser] parameters:nil success:nil failure:nil];
    

    更新

    RKRoute *locationUpdateRoute = [RKRoute routeWithClass:[Location class] pathPattern:@"users/:userID/locations/:locationID" method:RKRequestMethodPATCH];
    
    [[RKObjectManager sharedManager] patchObject:location path:nil parameters:nil success:nil failure:nil];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 2020-01-04
      • 1970-01-01
      • 2020-08-22
      • 2016-08-18
      相关资源
      最近更新 更多