ios - 如何计算属性中的记录数?

标签 ios swift core-data

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

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

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

最佳答案

我建议您编辑您的问题,以便为我们提供更多信息。

在没有您提供更多信息的情况下,此答案是根据我在尝试解释您的问题时的最佳猜测提供的。

一些可以提供帮助的基本术语。

Apple documentation表明你...

Model your data by describing your objects as entities, adding their properties as attributes and relationships, and finally generating respective NSManagedObject subclasses to inherit change tracking and life cycle management.

我可以建议你的问题写成这样可能更有意义:

是否可以计算与某个属性的特定值匹配的记录数?

如果我的猜测是正确的,您可以使用以下代码,并注意:

  • 该特定值是“要计数的属性值”;和
  • 属性是“testAttribute”。

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "TestEntity")
    
    let key = "testAttribute"                // the entity attribute
    let value = "attribute value to count"   // the attribute value
    
    let predicate = NSPredicate(format: "%K == %@", argumentArray: [key, value])
    
    request.predicate = predicate
    request.resultType = .countResultType
    
    var results: Int = 0
    
    do {
    
        results = try context.count(for: request)
    }
    catch {
    
        let fetchError = error
        print(fetchError)
    }
    

通过将 NSFetchRequestResultType 指定为 .countResultType,您要求提取请求仅计算与谓词匹配的指定实体的托管对象数量(其中“testAttribute”=“要计数的属性值”)。

这是一次非常高效的获取。

不会将托管对象提取到内存中 (例如,通过 var results: [NSManagedObject]? 得到的 NSManagedObject 数组),

确实仅将托管对象的数量提取到内存中 (例如,通过 var results: Int = 0NSManagedObject 进行计数)。

关于ios - 如何计算属性中的记录数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58175178/

相关文章:

swift - 通过索引访问字符串枚举

ios - 从核心数据数据库检索数据的替代方法 - ios

ios - 核心数据 SQLite 存储在更新后变为只读

ios - presentViewController :animated:YES view will not appear until user taps again

ios - 无法将 UIScrollView 设置为在 UITableViewCell 中滚动

ios - 如何在 Storyboard中选择多个 Controller ?

swift - 类型 ???没有成员

ios - 创建核心数据托管对象很困难

ios - <file>-Info.plist 无法打开,因为没有这样的文件

ios - XCode 5中的音频无法播放