通过断言CoreData iOS Swift从实体中查找重复的记录ID



如何使用coredata iOS Swift从实体中提取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")

应该用于计数

let countVariableExpr = NSExpression(forVariable: "count")

并且谓词将进行比较,其中count>1

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

编辑:
您当前正在按名称查找重复记录,如果您想按id查找,则如下所示:

let nameExpr = NSExpression(forKeyPath: "name")

需要更改为:

let idExpression = NSExpression(forKeyPath: "Id")

然后计数表达式将被更改为计数记录id。

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

编辑2:

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

还应更改为获取Id而不是名称

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

最新更新