【问题标题】:RestKit NSFetchRequest Block for deletion of orphaned objectsRestKit NSFetchRequest Block 用于删除孤立对象
【发布时间】:2014-02-09 12:40:58
【问题描述】:

我在我的 .com 域上托管了一个 Rest api,它在接收到这样的 www.mydomain.com/api/lists 请求时将返回 json 格式的数据,如下所示

[
    {"list_id":"1","listName":"List Name 1"},
    {"list_id":"2","listName":"List Name 2"},
    {"list_id":"5","listName":"List Name 3"},
    {"list_id":"7","listName":"List Name 4"},
    {"list_id":"8","listName":"List Name 5"},
    {"list_id":"11","listName":"List Name 6"},
    {"list_id":"12","listName":"List Name 7"}
]

现在我在我的 RKObjectManger 中添加一个 NSFetchRequest 块以使用此代码检查孤立对象

[objectManager addFetchRequestBlock:^NSFetchRequest *(NSURL *URL) {
        RKPathMatcher *pathMatcher = [RKPathMatcher pathMatcherWithPattern:@"/api/lists"];

        NSDictionary *argsDict = nil;
        BOOL match = [pathMatcher matchesPath:[URL relativePath] tokenizeQueryStrings:NO     parsedArguments:&argsDict];
        NSString *listID;
        if (match)
        {
            listID = [argsDict objectForKey:@"list_id"];
            NSLog(@"The listID is %@",listID);
            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
            NSEntityDescription *entity = [NSEntityDescription entityForName:@"List"
                                                      inManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];
            [fetchRequest setEntity:entity];
            fetchRequest.predicate = [NSPredicate predicateWithFormat:@"listID = %@", @([listID integerValue])]; 
            return fetchRequest;
        }

        return nil;
    }];

但我的listID = [argsDict objectForKey:@"list_id"]; 返回 nil,尽管从 web 返回的 json 中包含“list_id”。请指导我这里出了什么问题。

【问题讨论】:

  • 我的字典 argsDict 也是空的。任何人都可以告诉我为什么会这样吗?
  • 您的json 回复是Array

标签: ios objective-c json rest restkit


【解决方案1】:

你不能这样做:

listID = [argsDict objectForKey:@"list_id"];
NSLog(@"The listID is %@",listID);

因为路径模式/api/lists 中没有list_id 参数。因此,如果缺少此数据,您的谓词将始终检查错误的listID

但是,你不需要这些。假设请求从服务器返回所有对象——你应该使用 fetch 块的唯一时间——那么你不需要谓词。只需为实体创建一个获取请求并返回它而不使用任何谓词。

【讨论】:

  • 10,000 美元 - 不错!虽然我通常会满足于将答案打勾为正确;-)
  • @Wain 是否仅针对 GET 请求执行获取请求块?如果我对同一个 URL 有 POST 或 DELETE 操作(这对于 REST API 很常见)怎么办?
  • @MattBaker,是的,仅适用于 GET 请求。假设是 PUT / POST 正在创建/更新,因此响应应该只包含该对象,而不是一个更大的集合,清除是有意义的
  • @Wain 这就是我所期望的,但文档没有明确说明。谢谢!
猜你喜欢
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
相关资源
最近更新 更多