2016-04-25 40 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