开发者

iPhone Core Data - Access deep attributes with to many relationships

Let say I have an entity user which has a one to many relationship with the entity menu which has a one to many relationship with the entity meal which has a many to one relationship with the entity recipe which has a one to many relationship with the entity element. What I would like to do is to开发者_如何学C select the elements which belong to a particular user (username = myUsername) and particular menus (minDate < menu.date < maxDate).

Does anyone have an idea how to get them?

Thanks


You want to do a fetch on the element entity. From your description, it's not clear if you've defined the inverse relationships1 (e.g. element to recipie) and whether they are to-many or to-one. Assuming you have them defined and they are to-one, you can do your fetch with a predicate like [2]:

[NSPredicate predicateWithFormat:@"%@ > recipe.meal.menu.date && recipie.meal.menu.date < %@ && recipie.meal.menu.user.username LIKE[cd] %@", minDate, maxDate, myUsername];

I've used LIKE[cd] for a case-insensitive and diacritic-insensitive comparison on usename. Also note that Core Data stores dates as a double NSTimeInterval, without time-zone information. If you want to do timezone-sensitive date comparison, you're in for much more work.

1 If you haven't defined the inverse relationships, do it. As has been said many times elsewhere, Core Data is a graph management framework that just happens to be able to persist its graph to disk. It will do a lot of behind the scenes work to maintain referential integrity for you, automatically, if you define the inverse relationships. Particularly for many-to-many relationships, Core Data virtually requires the inverse to make things work.

[2] If you have defined to-many inverses where I've assumed to-one, you'll have to use a slightly more complicated predicate. The first clause, for example, would be

@"ANY (@unionOfSets.recipe.meal.menu.date) < %@"

(this last bit is untested; the KVO set operators are always a bit of experimenting for me). You can read up on the set and array KVO operators.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜