Which distinct logic does FetchRequest use with "returnsDistinctResults"?

If I use <FetchRequest.returnsDistinctResults> with unique "identifier" property, and there happened to be multiple NSManagedObjects in Core Data that contains the same "identifier", does the FetchRequest retrieve the latest modified/created object?

Is there a way to define the <FetchRequest.returnsDistinctResults> logic to be based on another property (e.g. "creationDate" / "modifiedDate") and the ascension order?

Answered by DTS Engineer in 855885022

A fetch request with returnsDistinctResults being true is converted to a SELECT DISTINCT at SQLite level. As far as I know, SQLite retains the first occurrence in the result set when handling DISTINCT, and so if you add modifiedDate as a (descendent) sort descriptor of your fetch request, you will be able to retain the last modified record when there are duplicates. I'd be really surprised if you see otherwise.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Accepted Answer

A fetch request with returnsDistinctResults being true is converted to a SELECT DISTINCT at SQLite level. As far as I know, SQLite retains the first occurrence in the result set when handling DISTINCT, and so if you add modifiedDate as a (descendent) sort descriptor of your fetch request, you will be able to retain the last modified record when there are duplicates. I'd be really surprised if you see otherwise.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Which distinct logic does FetchRequest use with "returnsDistinctResults"?
 
 
Q