【问题标题】:How to deal with partial relationship data returned while using AFIncrementalStore?使用 AFIncrementalStore 时返回的部分关系数据如何处理?
【发布时间】:2013-01-27 11:39:01
【问题描述】:

使用 AFIncrementalStore 进行实验,它非常棒。但是,我遇到了一个我不完全确定如何处理的情况。

我有一个模型,它返回子关系的 id,但不返回内容本身。例如: 获取/组

{"id":3,"description":"My Group","category_id":2}

我可以使用常规的 GET /categories 获取所有类别。但我没有调用 GET /group/3/categories

所以我不知道如何初始化group.category的子关系。我确定我遗漏了一些明显的东西,但我们将不胜感激。

有什么建议吗?

【问题讨论】:

    标签: iphone ios afnetworking afincrementalstore


    【解决方案1】:

    使用 AFIS 时,您存储的每个对象都有资源标识符。在大多数情况下,您希望对象的 id 为其 RI。所以在这种情况下 category_id 是您的类别对象的 RI。因此,您只能使用其 category_id 创建类别对象。然后,当您获得所有类别时,您将填充类别对象的其他字段。这很简单,因为 AFIS 足够聪明。

    还有另一种方法。由于您可以使用常规 GET /categories 获取所有类别,因此每个类别都应该有带有组 ID 的字段。因此,您可以设置从类别到它们的组的关系。它会自动建立反向关系。

    【讨论】:

      【解决方案2】:

      要以@nataliq 的回答为基础,这必须在您的 AFRESTClient 的representationsForRelationshipsFromRepresentation:ofEntity:fromResponse: 实现中。它应该以关系名称(“类别”)作为键,另一个以类别的 id 作为值的 NSDictionary。如果您的 Group 对象的 Category 关系被命名为“category”,并且您将其他对象的 id 属性以 _id 后缀命名,则可以执行以下操作:

      - (NSDictionary *)representationsForRelationshipsFromRepresentation:(NSDictionary *)representation
                                                                 ofEntity:(NSEntityDescription *)entity
                                                             fromResponse:(NSHTTPURLResponse *)response
      {
        NSMutableDictionary *mutableRelationshipRepresentations = [NSMutableDictionary dictionaryWithCapacity:[entity.relationshipsByName count]];
        [entity.relationshipsByName enumerateKeysAndObjectsUsingBlock:^(id name, id relationship, BOOL *stop) {
          id value = [representation valueForKey:[(NSString *)name stringByAppendingString:@"_id"]];
          if (value && ![value isKindOfClass:[NSNull class]] &&  ![relationship isToMany]) {
            NSDictionary *valueDict = @{@"id" : value};
            [mutableRelationshipRepresentations setValue:valueDict forKey:name];
          }
        }];
      
        return mutableRelationshipRepresentations;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多