I am writing a Mac app that uses Core Data as its persistence layer, and am curious as to what the general consensus is with the “ownership” of searches.
Let’s say that I have a class called Recipe (generated subclass of NSManagedObject) and I would like to be able to search for, say, “Recipes containing a certain ingredient”, “Recipes that can feed more than 4 people”, and so on. I can conceive methods like:
-(NSArray *)fetchRecipesContaining:(Ingredient *)ingredient;
-(NSArray *)fetchRecipesFeedingMorePeopleThan:(int)count;
and the implementation knows how to construct an appropriate NSFetchRequest/NSPredicate to go get them. The question is what object normally implements these methods? In a Java world, these would often live in an instance method on a RecipeFactory. I can also see the case for a class method in the Recipe class.
In a Hello World application (which most tutorials seem to offer) the logic is embedded directly in the invoking code, however, I am not that keen on having boilerplate code dealing with NSFetchRequests and NSEntityDescriptions scatted all through the invoking code. I really would prefer to abstract that logic away and allow a more meaningful API (per above) for fetching objects.
I am inclining towards a class method on Recipe (and implemented using categories so that I don’t have to modify the generated classes), but wanted to throw it out there and see what other Core Data users might use.
Thanks.
Use categories. As you note, this leaves the Xcode-generated classes untouched while allowing you to extend the functionality of the managed object class.