CoreData get distinct values of Attribute

前端 未结 4 2265
轻奢々
轻奢々 2020-12-02 08:06

I\'m trying to setup my NSFetchRequest to core data to retrieve the unique values for a specific attribute in an entity. i.e.

an entity with the follow

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 08:41

    This is a simple approach in Swift 5.x:

    // 1. Set the column name you want distinct values for
    let column = "name"
    
    // 2. Get the NSManagedObjectContext, for example:
    let moc = persistentContainer.viewContext
    
    // 3. Create the request for your entity
    let request = NSFetchRequest(entityName: "User")
    
    // 4. Use the only result type allowed for getting distinct values
    request.resultType = .dictionaryResultType
    
    // 5. Set that you want distinct results
    request.returnsDistinctResults = true
    
    // 6. Set the column you want to fetch
    request.propertiesToFetch = [column]
    
    // 7. Execute the request. You'll get an array of dictionaries with the column
    // as the name and the distinct value as the value
    if let res = try? moc.fetch(request) as? [[String: String]] {
        print("res: \(res)")
    
        // 8. Extract the distinct values
        let distinctValues = res.compactMap { $0[column] }
    }
    

提交回复
热议问题