2016-04-25 89 views
0

我想从fetchRequest筛选出结果中的重复项。我使用下面的代码:NSFetchRequest ReturnsDistinctResults给出空结果

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个项目。我的代码有什么问题?

+0

如果您打印'company_temp',您会得到什么?此刻你会发生崩溃吗? – Wain

+0

它是空的,只是'[]' –

回答

0

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

因此,简单的context.save()之前,您的代码可能会解决您的问题。

另一个问题是,这条线会崩溃:let company = company_temp as! [Details]因为你会得到一个Dictionary回来。不是列表NSManagedObject