我如何计算属性中的记录?

问题描述 投票:1回答:1

目前在ios中与核心数据有些纠缠,无法找到在当前Swift版本中有效的答案。是否可以计算属性中的记录数?

let results = try managedContext.fetch(request)
print (results.count)

这只是给我实体中所有记录的结果,但我需要从单个属性中了解它。谢谢!

ios swift core-data
1个回答
0
投票

您可以使用以下代码,这将给出perticular属性中的记录数。希望对您有所帮助:

let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "ENTITY")
let entity = NSEntityDescription.entity(forEntityName: "ENTITY", in: managedObjectContextInstance)
let statusDesc = entity?.attributesByName["attribute_name"]

fetch.propertiesToFetch = [statusDesc].compactMap { $0 }
fetch.resultType = .dictionaryResultType

var results: [Any]? = [Any]()
do {
    results = try mainManagedObjectContextInstance.fetch(fetch)
} catch { 
}
print(results.count)
© www.soinside.com 2019 - 2024. All rights reserved.