如何获取核心数据中用于属性的最频繁值?
假设我们的Entity表是:
--------------------------
| Name | Company |
--------------------------
| John | Boring Co. |
| Jane | Boring Co. |
| Robert | Boring Co. |
| Mary | MoneyPal Co |
| Jenn | MoneyPal Co |
--------------------------
我的目标是获得最多重复的值作为“公司”属性,即本例中的Boring Co.,而无需获取每个实体并尽可能遍历每个项目。
答案 0 :(得分:0)
我想分享一下我最终使用的内容,以防有人登陆此页面寻找类似问题的答案。我最初的意图是使用Core Data / SQL提取技术或某种特殊的谓词来实现这一目标,但我认为没有。因此,我实现了以下内容:
class CoreData_User:NSManagedObject{
static func getMostFrequentCompany(context: NSManagedObjectContext ) -> String?{
// We get a list of distinc Company entries
guard let companies:[String] = CoreData_User.getDistinctCompanies(context: context) else { return nil }
var maxRepeatedCompany:String = ""
var maxRepeatCount:Int = 0
// Then we loop through them to find which one is most oftenly used
for currentCompany in companies{
let currentCompanyRepeatCount:Int = CoreData_User.count(withCompany: currentCompany, context: context)
if currentCompanyRepeatCount > maxRepeatCount{
maxRepeatedCompany = currentCompany
maxRepeatCount = currentCompanyRepeatCount
}
}
if maxRepeatCount < 1 || maxRepeatedCompany.isEmpty {
return nil
} else {
return maxRepeatedCompany
}
}
static func getDistinctCompanies(context: NSManagedObjectContext ) -> [String]?{
let request:NSFetchRequest<NSFetchRequestResult> = CoreData_User.fetchRequest()
let companyAttributeName:String = "Company"
request.resultType = .dictionaryResultType
request.propertiesToFetch = [companyAttributeName]
request.returnsDistinctResults = true
var results:[String] = [String]()
context.performAndWait{
do{
guard let fetchResults = try context.fetch(request) as? [NSDictionary] else { return }
for item in fetchResults{
if let company = (item as AnyObject).value(forKey: companyAttributeName) as? String{
results.append(company)
}
}
} catch {
print("Failed to get company names")
}
}
if results.count > 0 {
return results
} else {
return nil
}
}
static func count(withCompany company: String, context: NSManagedObjectContext) -> Int{
let request = NSFetchRequest<T>(entityName: type.entity().name!)
request.includesSubentities = false
request.predicate = NSPredicate(format: "Company ==[c] %@", company)
var fetchResult:Int?
context.performAndWait{
fetchResult = try? context.count(for: request)
}
if let count = fetchResult {
return count
} else {
return 0
}
}
}
欢迎提出任何改进和优化方法的建议。