使用谓词搜索核心数据实体
我正在编写一个使用 Core Data 作为其持久层的 Mac 应用程序,并且很好奇搜索的“所有权”的普遍共识是什么。
假设我有一个名为 Recipe 的类(NSManagedObject 的生成子类),并且我希望能够搜索“包含某种成分的食谱”、“可以喂饱 4 人以上的食谱”等等。我可以设想这样的方法:
-(NSArray *)fetchRecipesContaining:(Ingredient *)ingredient;
-(NSArray *)fetchRecipesFeedingMorePeopleThan:(int)count;
并且实现知道如何构造适当的 NSFetchRequest/NSPredicate 来获取它们。问题是什么对象通常实现这些方法?在 Java 世界中,这些通常存在于 RecipeFactory 上的实例方法中。我还可以看到 Recipe 类中的类方法的情况。
在 Hello World 应用程序(大多数教程似乎都提供)中,逻辑直接嵌入到调用代码中,但是,我并不热衷于将处理 NSFetchRequests 和 NSEntityDescriptions 的样板代码分散在整个调用代码中。我真的更愿意抽象出该逻辑,并允许使用更有意义的 API(如上所述)来获取对象。
我倾向于在 Recipe 上使用类方法(并使用类别实现,这样我就不必修改生成的类),但想将其扔在那里,看看其他核心数据用户可能会使用什么。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用类别。正如您所注意到的,这使 Xcode 生成的类保持不变,同时允许您扩展托管对象类的功能。
Use categories. As you note, this leaves the Xcode-generated classes untouched while allowing you to extend the functionality of the managed object class.
我正在使用类方法的方法。我不确定它是否好,但还没有遇到任何麻烦。 Ruby on Rails 也使用它的 ActiveRecord 来到 Cocoa/CoreData - 这样做似乎很合乎逻辑,因为它在 ActiveRecord 库中也以相同的方式实现。
I'm using the approach with class methods. I wasn't sure if it's good, but haven't had any trouble with it yet. Also coming to Cocoa/CoreData from Ruby on Rails with it's ActiveRecord - it seemed only logical to do so, because it's implemented the same way in ActiveRecord library as well.