通过谓词CoreData iOS Swift从实体中查找重复记录ID

问题描述

如何使用iOS核心数据从实体数据中获取重复记录及其ID。我在下面使用,但没有得到正确的结果。任何建议将不胜感激。预先感谢。

func fetchDuplicateRecords() {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EmployeeData")
    
    let nameExpr = NSExpression(forKeyPath: "name")
    
    let countExpr = NSExpressionDescription()
    let countvariableExpr = NSExpression(forVariable: "Id")
    
    countExpr.name = "count"
    countExpr.expression = NSExpression(forFunction: "count:",arguments: [ nameExpr,nameExpr1,nameExpr2 ])
    countExpr.expressionResultType = .integer64AttributeType
    do {
        fetchRequest.resultType = .dictionaryResultType
        let idDescriptor: NSSortDescriptor = NSSortDescriptor(key: "Id",ascending: true)
        fetchRequest.sortDescriptors = [idDescriptor]
        
        fetchRequest.propertiesToGroupBy = ["name"]
        fetchRequest.propertiesToFetch = ["name",countExpr]
        fetchRequest.havingPredicate = nspredicate(format: "%ld > 1",countvariableExpr)
        
        //let results = try managedContext.execute(fetchRequest) as AnyObject
        let searchResults = try managedContext.fetch(fetchRequest)
        let resultsDict = searchResults as! [[String: Int32]]
        print("\(resultsDict)")
    } catch {
    }
}

解决方法

 let countVariableExpr = NSExpression(forVariable: "Id")

应该用于 count

let countVariableExpr = NSExpression(forVariable: "count")

然后谓词将比较count> 1

NSPredicate(format: "%@ > 1",countVariableExpr)

编辑:
您目前正在按其名称查找重复的记录,如果要按ID进行查找,则将是这样的:

let nameExpr = NSExpression(forKeyPath: "name")

需要更改为:

let idExpression = NSExpression(forKeyPath: "Id")

,然后count表达式将更改为count记录id。

NSExpression(forFunction: "count:",arguments: [idExpression])

编辑2:

fetchRequest.propertiesToGroupBy = ["name"]
fetchRequest.propertiesToFetch = ["name",countExpr]

还应该更改为获取 Id 而不是 name

fetchRequest.propertiesToGroupBy = ["Id"]
fetchRequest.propertiesToFetch = ["Id",countExpr]