如何解决通过谓词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]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。