我在 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
},
我已经在核心数据中设置了我的关系(与用户具有一对多关系的“writerUsers”),但我在弄清楚在 AFIS 中的何处配置它时失败了。
我尝试实现 - (NSDictionary *)representationsForRelationshipsFromRepresentation:(NSDictionary *)representation ofEntity:(NSEntityDescription *)entity fromResponse:(NSHTTPURLResponse *)response
但这似乎仅在服务器时才有效响应包含实际的对象值 - 整个用户实体,而不仅仅是 ID。
我还看到提到使用 - (NSURLRequest *)requestWithMethod:(NSString *)method
pathForRelationship:(NSRelationshipDescription *)关系
forObjectWithID:(NSManagedObjectID *)objectID
withContext:(NSManagedObjectContext *)context
提供 URL 请求来获取用户对象...但该方法永远不会从我的 AFHTTPClient 子类中调用。
那么,当我只有 ID 时,如何教 AFIncrementalStore 提取用户实体呢?
最佳答案
我的问题得到了解决。 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 将自动获取各个关系对象。
关于objective-c - AFIncrementalStore:仅使用 ID 拉取相关实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17960911/