Jayson Tamayo
Jayson Tamayo

Reputation: 2811

NSFetchRequest ReturnsDistinctResults gives empty results

I am trying to filter out the duplicate items in a result from a fetchRequest. I use the following code:

let sortDescriptor = NSSortDescriptor(key: "lastupdate", ascending: false)
        let sortDescriptors = [sortDescriptor]

        var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        var context:NSManagedObjectContext = appDel.managedObjectContext

        let fetchRequest = NSFetchRequest(entityName:"Details")
        fetchRequest.sortDescriptors = sortDescriptors
            fetchRequest.propertiesToFetch = [ "orig_id" ]
            fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType
            fetchRequest.returnsDistinctResults = true


        let company_temp = try context.executeFetchRequest(fetchRequest)
        let company = company_temp as! [Details]
        for t in company {
            let id = t.orig_id
            print(id)
            self.myarray.append("\(id)")

        }

When I comment out these 3 lines:

fetchRequest.propertiesToFetch = [ "orig_id" ]
            fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType
            fetchRequest.returnsDistinctResults = true

I get 8 items in my array. What is wrong with my code?

Upvotes: 0

Views: 195

Answers (1)

Raphael
Raphael

Reputation: 3886

Did you save your context?
I had the same problem. When you have unsaved changes, the NSDictionaryResultType does not reflect the current state of the persistent store. See Apple Docs about the includesPendingChanges: method.

So a simple context.save() before your code might fixes your problem.

Another problem is that this line will crash: let company = company_temp as! [Details] since you'll get a Dictionary back. Not a list of NSManagedObject.

Upvotes: 2

Related Questions