开发者

Core Data filtering on multiple entities

开发者 https://www.devze.com 2023-04-02 18:04 出处:网络
Lets assume we have an entity called \"Document\" and an other one called \"User\". There is a many-to-many relationship so a user can have a set of documents and each document can be owned by multipl

Lets assume we have an entity called "Document" and an other one called "User". There is a many-to-many relationship so a user can have a set of documents and each document can be owned by multiple users. Further documents have the attribute "type".

Now I want to fetch all documents for user x with the type "pdf". How would you access this data?

As far as I can see there are two ways:

  1. Retrieve all documents from the user by its relationship (user.documents) and filter the array with a NSPredicate (does that work with a complex object?).

  2. Do a fetch request on the "Documents" ent开发者_Go百科ity with two predicates. The first one specifies the user and the second one is responsible for the type.

Which is the better approach? Or is there even a better way to achieve this? I guess the second solution is much more expensive.


Your request's entity should be Document, and you need to use the ANY operation in your predicate:

[NSPredicate predicateWithFormat: @"ANY users == %@ AND type == %@", userX, @"PDF"];

See the section on Aggregate Operations:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html


Found the best way

NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray of Predicates]];

You can also use notPredicateWithSubpredicates and orPredicateWithSubpredicates depending on your needs.

Link to documentation http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSCompoundPredicate_Class/Reference/Reference.html


I've used Core Data for more than one year but I've just started to use relationships and other advanced features...
However, in my opinion, you can try to use the first way and to answer to your question, I advice you to read carefully the Predicate Programming Guide

0

精彩评论

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

关注公众号