0

Is it possible to set something like global rule for RKbjectManager to delete orphaned objects on successful mapping.

I am currently using RKPathMatcher to delete orphans for specific path pattern, but it just seems like I am missing something.

Dejan Zuza
  • 359
  • 1
  • 6
  • 14

1 Answers1

0

Read up on "Fetch Request Blocks" in RKManagedObjectRequestOperation, which are preconfigured NSFetchRequests to return all objects of the given type from your local storage, so that RestKit can find orphans that are no longer in the server response.

Their example block just checks for airport terminals:

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;
}];

but you can set the pathMatcher to match any pattern if your URLs are more general:

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;
}

Then you would just need the one fetch request block to match any of your entities.

Eric Hedstrom
  • 1,627
  • 10
  • 13
  • Thanks @Eric Hedstrom, guess this is closest i can get to that option with RestKit. – Dejan Zuza Jan 19 '17 at 22:12
  • So is there a reason why the sortDescriptor is included in the fetchRequest? Sort shouldn't be necessary to do a diff of the records, right? – deepwinter Oct 26 '17 at 01:51
  • @deepwinter Yes, I would guess that fetch request in the top example was copy/pasted from some other query code. You don't need sort descriptors for these fetch request blocks. – Eric Hedstrom Oct 26 '17 at 22:07