我知道如何使用a来获取带有谓词的核心数据 让谓词= NSPredicate(格式:" MyEntityAttribute ==%@","匹配值")。我想知道是否可以在不使用匹配值的情况下获取特定属性的所有值。我想获得特定属性的总值数。
这是我到目前为止所得到的,但我只回到与名称属性相匹配的内容。
let filter = "wayne"
let fetchRequest = NSFetchRequest<Likes>(entityName: "Likes")
let predicate = NSPredicate(format: "name == %@", filter)
fetchRequest.predicate = predicate
do {
let nameCount = try context.fetch(fetchRequest)
if nameCount.count >= 0 {
print("name exist")
}
} catch{
print(error.localizedDescription)
}
答案 0 :(得分:0)
我采用了不同的方法并使用NSFetchRequestResult来获取单个属性的结果。
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Likes")
fetchRequest.resultType = .dictionaryResultType
fetchRequest.propertiesToFetch = ["name"] // Single attribute I wanted to fetch
fetchRequest.returnsDistinctResults = true
do {
let result = try context.fetch(fetchRequest)
let resultDic = result as! [[String:String]]
print(resultDic.count)
print(resultDic)
} catch{
print(error.localizedDescription)
}