【问题标题】:AFIncrementalStore: Pulling a Related Entity with ID OnlyAFIncrementalStore:仅使用 ID 拉取相关实体
【发布时间】:2013-07-31 03:07:35
【问题描述】:

我在我的 Mac 应用程序中使用 App.net 消息传递 API,它使用 Core Data 和 AFIncrementalStore。我有一个Channel 实体,它有几种不同的方式与Users 实体相关联。有一个简单且工作正常的“所有者”关系。但也有两个ACL 实体:Channel 的读者和作者。

ACL 只是一个包含用户 ID 数组的键值对对象,这是我不确定如何使用 AFIncrementalStore 处理的关系。

我正在拉取一个 Channel 实体,它附加了一个 ACL 对象(“writers”),其中包含一组用户 ID:

"writers": {
    "any_user": false,
    "immutable": true,
    "public": false,
    "user_ids": [
        "1",
    ],
    "you": true
},

我已经在 Core Data 中设置了我的关系(“writerUsers”与用户之间存在一对多关系),但我在 AFIS 中搞不清楚在哪里配置它。

我已经尝试实现 - (NSDictionary *)representationsForRelationshipsFromRepresentation:(NSDictionary *)representation ofEntity:(NSEntityDescription *)entity fromResponse:(NSHTTPURLResponse *)response,但这似乎只有在服务器响应包含实际对象值时才有效——整个用户实体,而不仅仅是 ID。

我还看到有人提到使用 - (NSURLRequest *)requestWithMethod:(NSString *)method pathForRelationship:(NSRelationshipDescription *)relationship forObjectWithID:(NSManagedObjectID *)objectID withContext:(NSManagedObjectContext *)context 提供 URL 请求以获取用户对象...但该方法永远不会从我的 AFHTTPClient 子类中调用。

那么当我只有一个 ID 时,如何教 AFIncrementalStore 拉入用户实体?

【问题讨论】:

  • 您好,我也有类似的问题。您找到任何解决方案了吗?
  • 很遗憾没有。我在这个问题上的赏金没有产生任何结果,对 AFIS 维护者的请求失败了,并且没有文档和相互冲突的信息。有效吧。我最终推出了自己的解决方案,它就像一个冠军。
  • @lari,对这个问题有什么见解吗? stackoverflow.com/questions/19294613/…

标签: objective-c cocoa core-data afincrementalstore


【解决方案1】:

我能够解决我的问题。 API 在 json 中应该有这种格式:

"users": [
    {"id":1},
    {"id":2}
]

即使 API 不提供这种格式的数据,您也可以在 AFRESTClient 的子类中“伪造”它。

- (NSDictionary *)representationsForRelationshipsFromRepresentation:(NSDictionary *)representation
                                                       ofEntity:(NSEntityDescription *)entity
                                                   fromResponse:(NSHTTPURLResponse *)response {

    NSMutableDictionary *mutableRelationshipRepresentations = [[super representationsForRelationshipsFromRepresentation:representation ofEntity:entity fromResponse:response] mutableCopy];
    if ([entity.name isEqualToString:@"writer"]) {
        NSArray *user_ids = [representation objectForKey:@"user_ids"];
        NSMutableArray *users = [[NSMutableArray alloc] init];
        for (NSNumber *id in user_ids) {
            [users addObject:@{@"id":id}];
        }
    }
    [mutableRelationshipRepresentations setObject:users forKey:@"users"];

    return mutableRelationshipRepresentations;
}

当然你需要在模型中将“用户”定义为一对多关系。当关系对象中只有 id 时,AFIncrementalStore 会自动获取各个关系对象。

【讨论】:

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