Dumbfounded

I was just shown an NSPredicate that dumbfounded me for several reasons:

  1. It’s using five nested SUBQUERY expressions. In other words, a SUBQUERY within a SUBQUERY within a SUBQUERY within a SUBQUERY within a SUBQUERY.
  2. It works
  3. It’s reasonably fast
  4. Core Data correctly handles it on a SQLite store
  5. It’s the only way the author could accomplish what he needed in a “reasonable” way.

What sort of NSPredicate is this? Here you go:

static NSString *kCommonRequestFragment = @"SUBQUERY(things, $thing, SUBQUERY($thing.thingType.spams, $spam, SUBQUERY($spam.ham.eggs, $egg, SUBQUERY($egg.foo.bars, $bar, SUBQUERY($bars.baz.blips, $blip, $blip.bing.id == %@).@count > 0).@count > 0).@count > 0).@count > 0).@count > 0";

- (NSFetchRequest *)fetchRequestForSomeObjects {
    NSFetchRequest *theRequest = [self templateFetchRequest];
    NSString * thePredicateFormatString = [NSString stringWithFormat:@"(%@) AND (%@)", @"SUBQUERY(participatingObjects, $object, $object.property.id == %@).@count > 0", kCommonRequestFragment];
    [theRequest setPredicate:[NSPredicate predicateWithFormat:thePredicateFormatString, self.aThing.anID, self.aThing.anotherID]];

    return theRequest;
}

- (NSFetchRequest *)fetchRequestForOtherObjects {
    NSFetchRequest *theRequest = [self templateFetchRequest];
    NSString * thePredicateFormatString = [NSString stringWithFormat:@"(%@) AND (%@)", @"SUBQUERY(participatingObjects, $object, $object.property.id == %@).@count == 0", kCommonRequestFragment];
    [theRequest setPredicate:[NSPredicate predicateWithFormat:thePredicateFormatString, self.aThing.anID, self.aThing.anotherID]];

    return theRequest;
}

Insane.

  1. alexeckermann reblogged this from funwithobjc
  2. funwithobjc posted this
Short URL for this post: http://tmblr.co/Zt522y6oX7Js
blog comments powered by Disqus