M. Ryan
M. Ryan

Reputation: 7192

NSFetchRequest and NSPredicate, array comparison and matching

Class A contains a toMany relationship to Class C

Class B contains a toMany relationship to Class C

I'm seeking to design an NSFetchRequest which queries objects based on the notion that the relationships to Class C have at least one object in common between instances of Class A and Class B

I lack the proper language to describe this concept, but feel like it must be possible purely within some scheme of NSPredicates

So if Object A (a-0) is related to Objects C (c-2, c-4)

and Object B (b-0) is related to Objects C (c-0, c-4)

Then the predicate considers that a match

But if Object B (b-0) was related to Objects C (c-0, c-1)

then that would not be considered a match

My nonworking predicate started like this

[NSPredicate predicateWithFormat:@"obja.objectsC IN %@", objb.objectsC];

Which is simply disallowed by CoreData, but wanted to provide that as a frame of reference against what the correct answer might be.

Upvotes: 1

Views: 108

Answers (1)

byzyn4ik
byzyn4ik

Reputation: 124

  1. You cant simply match array in the array because you can only match object in the array.
  2. The solution for such situation is using SUBQUERY. We will iterate all objects in obja.objectsC to match is an object in objb.objectsC. After that, we counting all references and comparing with zero.

[NSPredicate predicateWithFormat:@"SUBQUERY(obja.objectsC, $objA, $objA IN %@).@count > 0", objb.objectsC];

Upvotes: 2

Related Questions