【问题标题】:CoreData Optimization Issue (Swift)CoreData 优化问题 (Swift)
【发布时间】:2020-06-09 21:23:28
【问题描述】:

我有 CarStyle 具有多对多关系的模型,我可以选择按它们的样式过滤汽车。所以我使用这样的谓词:

    var subpredicates: [NSPredicate] = []

    let ids: Set<NSManagedObjectID> = // Get ids of Styles

    for id in ids {
        subpredicates.append(NSPredicate(format: "ANY styles == %@", id))
    }

    let predicate = NSCompoundPredicate(orPredicateWithSubpredicates: subpredicates)

然后用它来获取计数:

    let fetchRequest = NSFetchRequest<Car>(entityName: "Car")
    fetchRequest.predicate = predicate
    let count = (try? context.count(for: fetchRequest)) ?? 0

当样式数超过 11 时会出现问题。过滤 12 个样式需要 1 秒,过滤 13 个样式需要 3 秒,过滤 14 个样式需要 9 秒,过滤 15 个样式需要 25 秒。

【问题讨论】:

    标签: swift xcode core-data


    【解决方案1】:

    尝试使用 SUBQUERY:

    let predicate = NSPredicate(format: "SUBQUERY(styles, $S, $S IN %@).@count > 0", id)
    

    这避免了使用 ANY,这意味着您可以使用 IN 而不是复合谓词。这在解析谓词字符串和执行 fetch 时应该更有效,但它是否真的会更快地运行,我留给你测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 2011-07-15
      • 2011-04-01
      • 2019-03-12
      • 2010-10-20
      相关资源
      最近更新 更多