countForFetchRequest and executeFetchRequest return different numbers of results
I'm finding that a NSFetchRequest is returning different results for a count and for an execute.
I have a Product entity and a Size entity. A Product has many Sizes.
I have two products, productA and productB. ProductA is only available in size1 and productB is available in both size1 and size2.
Given the NSPredicate
'ANY sizes.#size IN {"size1", "size2"}
'
I'm finding that it returns 3 for the countForfetchRequest
but an array 开发者_Python百科of 2 items when I execute the fetch request.
The count is the value that is incorrect. ProductB has both sizes and seems to be being counted twice in the countForfetchRequest
but obviously only returned once by the executeFetchRequest
call.
I've tried setting setReturnsDistinctResults:YES
with no effect.
I have slightly modified the predicate in the answer. Note that the same considerations regarding the parsing problems you may encounter (given in one of my previous comment) still apply. I am assuming that you have multiple sizes, say sizeA, sizeB, sizeC etc. You need a subquery to deal correctly with your to-many relationship in Core Data, as shown in the following predicate
EDIT:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(sizes.@count == 1 || sizes.@count == 2) && (1 == SUBQUERY(sizes, $sub, $sub.#size == %@ || $sub.#size == %@).@count || 2 == SUBQUERY(sizes, $sub, $sub.#size == %@ || $sub.#size == %@).@count)", yourSizeAvariable, yourSizeBvariable];
Let me know if this works correctly for you.
I think when you do a count, it is counting the number of rows returned from the sql query. As you are querying the size table, you get back 3 because the equivalent sql would return 3 rows.
When you do a fetch, you get 2 because you will only get back two product objects. However if you looked inside those products to the number of size objects, you will find 3.
Oh, and the select distinct will not work because you have 3 unique sets of values :-)
精彩评论