NSPredicate for searching within relationship entities

cannyboy picture cannyboy · Aug 15, 2011 · Viewed 12.4k times · Source

I have an entity called Band which has a to-many relationship to a Category entity. The Category entity just contains a categoryName string attribute.

An example record:

Band:       
  bandName: Kiss
  bandCategories:   -  > BandCategory:categoryName:Glam
                    -  > BandCategory:categoryName:Rock

How would I use NSPredicate to search thru all my Bands for bands which match the Rock category, for example?

Answer

Joe picture Joe · Aug 15, 2011

According to the NSPredicate Programming Guide you will need to specify the key path to categoryName with the ANY or ALL specifier.

NSString *category = @"Rock";
[NSPredicate predicateWithFormat:@"ANY bandCategories.categoryName == %@", category];