NSFetchRequest ReturnsDistinctResults给出空结果

时间:2016-04-25 14:27:04

标签: swift

我正在尝试从fetchRequest中过滤掉结果中的重复项。我使用以下代码:

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)")

        }

当我评论这3行时:

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

我的数组中有8个项目。我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

您是否保存了上下文?
我有同样的问题。当您有未保存的更改时,NSDictionaryResultType不会反映持久性存储的当前状态。有关includesPendingChanges:方法,请参阅Apple Docs

在您的代码可能修复您的问题之前,这是一个简单的context.save()

另一个问题是此行会崩溃:let company = company_temp as! [Details]因为您将获得Dictionary。不是NSManagedObject的列表。