开发者

Core Data: How to do a second fetch limited to the results of an earlier fetch?

开发者 https://www.devze.com 2023-03-02 09:14 出处:网络
This seems like it may be a trivial question, but I am new to Core Data and to databases. In my application, I perform a fetch and display the results.Then, based on user input, I need to cull those

This seems like it may be a trivial question, but I am new to Core Data and to databases.

In my application, I perform a fetch and display the results. Then, based on user input, I need to cull those results down. That is, I need to do a new search on only the results of the first fetch, but based on an entirely different parameter. (Sometimes, the second fetch will be based on an attribute, other times on a to-many relationship.) What is the optimal way to do thi开发者_Go百科s?

I have figured out two options to do this, but neither seems very good:

  1. In the first fetch, prefetch all the data needed for the second fetch. Then, don't do a second fetch, but just iterate through the array of results of the first fetch, looking for matches to the new conditions of the second fetch. This method has the disadvantage that I have to trudge thru the array and don't take advantage of performance benefits of Core Data.

  2. For the second fetch, disregard the first and do a brand new fetch with a compound predicate composed of the conditions for the first fetch and those for the second. This has the disadvantage that Core Data must look thru the entire database again to do the same search it already did.

Is there a way, in a second fetch, to tell Core Data to search only thru the entity objects returned in an earlier fetch?


You've pretty much got it figured out.

For the first option, it's pretty easy. You have your array of objects, and you can just do -[NSArray filteredArrayUsingPredicate:] or -[NSMutableArray filterUsingPredicate:] to reduce the array according to your needs. You don't need to actually iterate through the array yourself; just use a predicate like you would with a fetch request.

For the second option, that's also pretty easy. You take the predicate from your first request and AND it with your new predicate:

NSPredicate *original = ...;
NSPredicate *newCondition = ...;
NSPredicate *newFilter = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:original, newCondition, nil]];

Personally, I usually find the first option to be simpler overall.

0

精彩评论

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

关注公众号