与核心数据 swift 不同的价值

Nit*_*thu 1 database xcode core-data swift

我想从核心数据中获取不同的日期。使用此代码 fetchRequest.returnsDistinctResults = true 不起作用。它仍然显示所有值。

guard let appDelegate =
          UIApplication.shared.delegate as? AppDelegate else {
            return
        }
    
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Journal")
    
    
    fetchRequest.propertiesToFetch = ["dateAsNumber"]
    fetchRequest.returnsDistinctResults = true

    do {
    
        dateListSquare = try managedContext.fetch(fetchRequest)
        
    } catch let error as NSError {
      
        print("Could not fetch. \(error), \(error.userInfo)")
    }
Run Code Online (Sandbox Code Playgroud)

Tom*_*ton 5

如果您想要不同的结果,则需要将获取请求的结果类型设置为NSFetchRequestResultType.dictionaryResultType. 您无法获取托管对象并获得不同的结果,因为可能有多个托管对象具有相同的值。

那看起来像

let fetchRequest: NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: "Journal")
fetchRequest.propertiesToFetch = ["dateAsNumber"]
fetchRequest.returnsDistinctResults = true
fetchRequest.resultType = .dictionaryResultType
Run Code Online (Sandbox Code Playgroud)

结果将是一个字典数组。每个条目的每个条目都有一把钥匙propertiesToFetch(在本例中只有一把)。

如果使用propertiesToFetchwithout dictionaryResultType,则会影响故障的工作方式,但不会影响结果的内容。returnsDistinctResults仅当您也使用 时,使用才有效propertiesToFetch,因此它也受到您是否使用 的影响dictionaryResultType