RestKit删除孤立对象规则

时间:2017-01-19 13:43:43

标签: ios swift swift3 restkit ios10

是否可以设置类似于全局规则的内容 RKbjectManager在成功映射时删除孤立对象。

我目前正在使用RKPathMatcher删除特定路径模式的孤儿,但似乎我错过了一些东西。

1 个答案:

答案 0 :(得分:0)

阅读RKManagedObjectRequestOperation中的“获取请求块”,它们是预先配置的NSFetchRequests,用于从本地存储返回给定类型的所有对象,以便RestKit可以找到不再在服务器响应中的孤立。

他们的示例块只检查机场航站楼:

RKObjectManager *manager = [RKObjectManager managerWithBaseURL:@"http://restkit.org"];
[manager addFetchRequestBlock:^NSFetchRequest *(NSURL *URL) {
    RKPathMatcher *pathMatcher = [RKPathMatcher pathMatcherWithPattern:@"/airports/:airport_id/terminals.json"];

    NSDictionary *argsDict = nil;
    BOOL match = [pathMatcher matchesPath:[URL relativePath] tokenizeQueryStrings:NO parsedArguments:&argsDict];
    NSString *airportID;
    if (match) {
        airportID = [argsDict objectForKey:@"airport_id"];
        NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Terminal"];
        fetchRequest.predicate = [NSPredicate predicateWithFormat:@"airportID = %@", @([airportID integerValue])]; // NOTE: Coerced from string to number
        fetchRequest.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES] ];
        return fetchRequest;
    }

    return nil;
}];

但如果您的网址更为通用,则可以将pathMatcher设置为匹配任何模式:

RKPathMatcher *entityMatcher = [RKPathMatcher pathMatcherWithPattern:@"/tables/:entityName"];

BOOL entityMatch = (pathAndQueryString != nil) && [entityMatcher matchesPath:pathAndQueryString tokenizeQueryStrings:YES parsedArguments:&argsDict];
if (entityMatch) {
  NSString *entityName = argsDict[@"entityName"];

  NSFetchRequest *fetchRequest;
  if (entityName) {
    fetchRequest = [NSFetchRequest fetchRequestWithEntityName:entityName];
    fetchRequest.includesSubentities = NO;
  }

  return fetchRequest;
}

然后你只需要一个获取请求块来匹配你的任何实体。